How to create a symbol from a string that has whit

2020-05-26 09:41发布

I am creating a Ruby hash for movie names storage.

When the hash's keys are strings that contains whitespaces, it works just fine.

As in:

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

Now I am trying to replace the use of strings with symbols:

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

Obviously that doesn't work.

How does Ruby handle whitespaces in symbol naming?

4条回答
Animai°情兽
2楼-- · 2020-05-26 10:07

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 
查看更多
ら.Afraid
3楼-- · 2020-05-26 10:08

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}
查看更多
Emotional °昔
4楼-- · 2020-05-26 10:14

Try by yourself

"Lord of the rings".to_sym
#=> :"Lord of the rings"
查看更多
ゆ 、 Hurt°
5楼-- · 2020-05-26 10:22

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}
查看更多
登录 后发表回答