How to create a symbol from a string that has whitespaces?

不想你离开。 提交于 2019-12-03 03:14:06

Try by yourself

"Lord of the rings".to_sym
#=> :"Lord of the rings"

I'm not sure why you want to use symbols when you want spaces in the key values, but you can do that. You just can't do it using the <symbol>: <value> syntax...

{:Avatar => 5, :"Lord of the rings" => 4, :Godfather => 4}

To make a symbol with spaces, enter a colon followed by a quoted String. For your example, you would enter:

movies = {:Avatar => 5, :'Lord of the rings' => 4, :Godfather => 4}
pinkninja

Late to the party, but another way to get around this is to do the following:

movies = Hash.new

movies["the little mermaid".to_sym] = 4 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!