Ruby 用新的哈希值更新哈希值
我提示用户添加一个新的评级以附加旧的评级,但该值仍然保持不变。我做错了什么Ruby 用新的哈希值更新哈希值,ruby,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 t
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
原因是更新程序是一个字符串,而散列是符号访问的。替换:
movies[updater]=rating.to_i
与
movies[updater.to_sym]=rating.to_i
似乎我忘了在这里将更新程序转换为符号。这解决了问题!