2013-10-27 43 views
0

我必须更新并添加一个电影标题及其相关的评级到现有的哈希。这是代码,我到目前为止有:哈希和case语句

movies = { 
Titanic:4, 
Bestman: 3, 
Agora: 2 
} 

puts "What would you like to do?" 
choice = gets.chomp 

case movies 
when "add" 
    puts "What movie do you want to add?" 
    title = gets.chomp 
    puts "What's the rating of the movie?" 
    rating = gets.chomp 
    movies[title] = rating 
    puts "#{title} has been added with a rating of #{rating}." 

when "update" 
puts "Updated!" 
when "display" 
puts "Movies!" 
when "delete" 
puts "Deleted!" 
else 
    puts "Error!" 
end 

当我运行代码,我得到这个错误“它看起来像你没有加入到电影哈希”

我知道错误的谎言介于这字里行间:

case movies 
when "add" 
    puts "What movie do you want to add?" 
    title = gets.chomp 
    puts "What's the rating of the movie?" 
    rating = gets.chomp 
    movies[title] = rating 
    puts "#{title} has been added with a rating of #{rating}." 

我一直在试图弄明白,但迄今未能找出我做错了。

有没有其他方法可以添加到我的电影哈希?我的放入代码让用户知道他/她的电影名称和评级已添加,这有什么问题?

谢谢

编辑 正如所指出的一些盖伊,从

case movies 

改变case语句

case choice 

解决了这个问题。

我需要学习/弄清楚为什么第二个作品,但第一个没有。

+2

你可能想选择的情况下,而不是案件的电影 –

+0

这工作!如果您不介意,请解释为什么使用电影会导致我的代码无效 - 我将非常感谢您的反馈,谢谢! – Uzzar

+0

电影是你的散列,但你希望case语句对你的输入起作用,它存储在变量'choice'中。 –

回答

0

如果它仍然是不明确的,它可以帮助想一个case语句为一系列IF/ELSIF的(也有差异,但这种情况下它的工作原理),所以:

case movies 
when "add" # do stuff 

类似于到:

if movies == "add" 
    # do stuff 
end 

希望能说得更清楚。

+0

我其实更了解第一种解释 - case语句应该对用户提供的输入起作用,并且由于case语句包含在一个名为movies的容器中,因此确保为case语句给出/编写的命令是有意义的特定于案例陈述容器 - 这就是单独的案例代码行为。那有意义吗?我实质上是在试图将程序分解为离散单元并编写适用于每个特定单元的代码/确保我知道每行代码的作用或影响。 – Uzzar

1

变化

case movies 

case choice # because this is where your choice of what to do is being stored