我阅读了一种创建哈希的方法,如下所示。当我尝试添加已经存在的电影时,ruby 不会返回正确的字符串。如果我放置一个常规哈希(例如movies
= {Pirates: 3, James_Bond: 4}
),它会正确返回。谁能解释为什么会这样?
movie = %w(Pirates James_Bond Finding_Nemo)
rating = [4, 3, 5]
movies = Hash[movie.zip(rating)]
puts "What would you like to do?"
choice = gets.chomp
case choice
when "add"
puts "What title would you like to add?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "What is the rating of this movie?"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
else
puts "Movie already exists."
end
end