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

前端 未结 4 909
南笙
南笙 2021-02-05 14:35

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 =

相关标签:
4条回答
  • 2021-02-05 14:54

    Try by yourself

    "Lord of the rings".to_sym
    #=> :"Lord of the rings"
    
    0 讨论(0)
  • 2021-02-05 15:07

    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}
    
    0 讨论(0)
  • 2021-02-05 15:11

    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}
    
    0 讨论(0)
  • 2021-02-05 15:12

    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 
    
    0 讨论(0)
提交回复
热议问题