Ruby:如何使用/将多字符串转换为符号

时间:2015-02-02 15:43:28

标签: ruby hash key symbols

大多数哈希键都是单个词名。我们以电影名称和评级为例。这很容易做出符号:

my_hash = { Ferris_Bueller: 5}

如果我不想在我的密钥名称中使用下划线,但需要将该字符串作为符号,该怎么办? 我想过这样做,但它不起作用:

my_hash = { "Ferris Bueller": 5}

问题是,我尝试提示用户为电影命名,评分,然后将这些值添加为my_hash中的键/值对。人们会正常输入双字电影,没有下划线。如何将该密钥作为符号存储在哈希中?即:

puts "Name a movie:" name = gets.chomp puts "Rate it 1-5:" rating = gets.chomp my_hash[name.to_sym] = rating

用户输入双字电影,例如Robo Cop。为什么不这样做?

2 个答案:

答案 0 :(得分:1)

你也可以使用.gsub!将_转换为空格然后转换为.gsub!再次将其转换回来。这样代码仍然会注册,但用户永远不会看到下划线。这是一个例子:

movies = {
The_Raven: 4,
I_Robot: 3
}

puts "Howdy, please select one of the following."
choice = gets.chomp
case choice
when "update"
puts "Please select which movie you'd like to update."
title = gets.chomp
title.gsub!(/ /, "_")
#By doing this, the user can type 'The Raven' and Ruby will be able to
#register it as a title in your movies hash.
if
    movies[title.to_sym].nil?
    puts "That movie doesn't exist in our inventory!"
else 
    puts "What would you like to change the rating to? (Rating must be 1 - 5)"
    rating = gets.chomp
    movies[title.to_sym] = rating.to_i
    title.gsub!(/_/, " ")
#Then you convert it back from an underscore to a space. This way Ruby 
#will display to the user the title without underscores. 
    puts "#{title} has been updated with a new rating of #{rating}."
end`enter code here`

答案 1 :(得分:0)

为了实现这一点,你可能需要实际使用哈希火箭......

my_hash = { :"Ferris Bueller" => 5}