2013-10-27 42 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