Ruby - 意外的keyword_when,期待keyword_end

时间:2014-05-18 16:48:52

标签: ruby

在case语句中输入两个块时,我收到此消息两次。无法找到问题。

choice = gets.chomp.downcase!

case = choice

when "update"
puts "Enter the title of the movie to be updated."
title = gets.chomp.to_sym

    if movies[title] == nil
        puts "This movie is not in the system."
    else
        puts "Input the new rating."
        rating = gets.chomp.to_i
        movies[title] = rating
        retry if (rating < 0 || rating > 5)  
                    puts "This rating is invalid! Try again."
                end

    end

when "display"
movies.each do |title, rating|
    puts "#{title}: #{rating} / 5 stars"
    end
end

代码块进一步向下延伸到“when”的更多实例,但为了简单起见,我决定截断它。如有必要,我可以提交完整的代码。错误具体如下:

    (ruby):57: syntax error, unexpected keyword_when, expecting keyword_end
     when "update"
     ^
    (ruby):72: syntax error, unexpected keyword_when, expecting $end
     when "display"
     ^

2 个答案:

答案 0 :(得分:3)

您看到的错误是因为您的语法错误。缩进代码时要非常小心,这样可以更容易地找到这些错误:

choice = gets.chomp.downcase!

case choice

when "update"
  puts "Enter the title of the movie to be updated."
  title = gets.chomp.to_sym

  if movies[title] == nil
    puts "This movie is not in the system."
  else
    puts "Input the new rating."
    rating = gets.chomp.to_i
    movies[title] = rating
    # retry if (rating < 0 || rating > 5)  
    puts "This rating is invalid! Try again."
  end

when "display"
  movies.each do |title, rating|
    puts "#{title}: #{rating} / 5 stars"
  end
end

end之前还有一个when "display"。我想这是为了关闭if (rating < 0 || rating > 5),但因为它之前是一个声明,所以它是one line if statement

即使修复了,retry也被误用了。由于不清楚您究竟想要做什么,我对其进行了评论 - 我建议您阅读相关documentation重新编写正确的retry语法,并相应地重新编写代码。

答案 1 :(得分:0)

我想这一行case = choice应该只是case choice

   choice = gets.chomp.downcase!

   case choice

   when "update"
    puts "Enter the title of the movie to be updated."
    title = gets.chomp.to_sym

    if movies[title] == nil
      puts "This movie is not in the system."
    else
      puts "Input the new rating."
      rating = gets.chomp.to_i
      movies[title] = rating
    if (rating < 0 || rating > 5)  
      puts "This rating is invalid! Try again."
    end

  when "display"
   movies.each do |title, rating|
    puts "#{title}: #{rating} / 5 stars"
  end
end