使用新的哈希值更新哈希值

时间:2014-01-19 09:04:41

标签: ruby

我提示用户添加新评级以附加旧评级,但值仍然保持不变。我在这里做错了什么?

movies = { the_dark_knight: 9, mrs_doubtfire: 8.5 }
    puts "***** Welcome to the movie guide!! ***** "
    puts "***** Enter a choice! *****"
choice = gets.chomp

case choice
when "add"
    puts "Please enter the title of the movie"
title = gets.chomp
    puts "Now enter your rating for this movie!"
rating = gets.chomp
    if movies[title.to_sym] == nil
        movies[title.to_sym] = rating.to_i
    else puts "That movie already exists!"
    end


when "update"
    puts "Enter the title that you would like to update!"
updater = gets.chomp
if movies[updater.to_sym] == nil
    puts "This movie does not exist in the database!"
else puts " Ok! What is your new rating?"
    rating = gets.chomp
    movies[updater] = rating.to_i
    movies
end

1 个答案:

答案 0 :(得分:1)

原因是您的updater是一个字符串,而哈希是符号访问的。替换:

movies[updater] = rating.to_i

movies[updater.to_sym] = rating.to_i