【问题标题】:Ruby hash["string".to_sym].nil? keeps returning true regardless of key item exist or notRuby hash["string".to_sym].nil?无论关键项目是否存在,都保持返回true
【发布时间】: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


    【解决方案1】:

    试试

    movies[title.gsub(' ', '_').to_sym]
    

    符号化字符串不会将空格转换为下划线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 2016-07-31
      • 1970-01-01
      相关资源
      最近更新 更多