我读了一种创建哈希的方法,如下所示。当我尝试添加已存在的电影时,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
答案 0 :(得分:4)
就是这样。
movies[title.to_sym] = rating.to_i
%w
运算符创建字符串数组,而不是符号。你应该这样做:
movies[title.to_s] = rating.to_i
或者您可以使用%i
运算符创建符号数组。选择你真正想要的运营商(感谢@muistooshort)
%w(Pirates James_Bond Finding_Nemo) # => ["Pirates", "James_Bond", "Finding_Nemo"]
%i(Pirates James_Bond Finding_Nemo) # => [:Pirates, :James_Bond, :Finding_Nemo]