【发布时间】:2015-02-21 04:53:46
【问题描述】:
我一直在尝试搜索并弄清楚为什么使用 something["string".to_sym].nil?它总是返回 true。例如:
movies = {
the_matrix: 5,
sin_city: 3.5,
days: 1
}
puts "What would you like to do?"
puts "*** Type add to add a movie."
choice = gets.chomp
case choice
when "add"
puts "Please input the movie title:"
title = gets.chomp
if movies[title.to_sym].nil? #check to see if the movie title exists
puts "What rating would you give this movie?"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
else
puts "The movie title is in the database!"
end
else
puts "Error!"
end
似乎语法 .to_sym 仅适用于单字输入。
当我输入“days”时,它给出了正确的响应:“电影名称在数据库中!”
当我在提示后键入“矩阵”时,它不会识别电影已经在哈希中,而是询问电影的评级。
我做了一些测试,发现
movies[title.to_sym].nil?
无论标题是否包含多个单词,都始终返回 true。我在这里错过了什么吗?
【问题讨论】:
标签: ruby-on-rails ruby symbols