1

我阅读了一种创建哈希的方法,如下所示。当我尝试添加已经存在的电影时,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
4

1 回答 1

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]
于 2013-11-06T05:46:35.513 回答