14

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?

Jonathan Soifer
  • 2,715
  • 6
  • 27
  • 50
swapnesh
  • 26,318
  • 22
  • 94
  • 126

4 Answers4

19

Try by yourself

"Lord of the rings".to_sym
#=> :"Lord of the rings"
oldergod
  • 15,033
  • 7
  • 62
  • 88
  • 1
    but why this is not working ? movies = {Avatar: 3, "Lord of the rings": 4 } However it does movies = {Avatar: 3, :"Lord of the rings" => 4 } – swapnesh Mar 12 '13 at 04:57
  • 3
    @swapnesh: That doesn't work because the JavaScript-style notation only works with [some symbols](http://stackoverflow.com/a/10004344/479863) and [symbols with spaces don't qualify.](http://stackoverflow.com/a/8675314/479863) – mu is too short Mar 12 '13 at 05:17
  • 4
    Note that this solution will apparently create a string instance, and then resolve or create a matching symbol instance (unless the optimizer is smart enough to avoid that). Declaring a symbol with the `:""` syntax should simply resolve or create the symbol without creating and discarding a string object first. So -- if the purpose of using symbols is to optimize... – Steve Jorgensen Mar 12 '13 at 06:38
7

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}
Steve Jorgensen
  • 11,725
  • 1
  • 33
  • 43
  • I am trying to do this just bcoz symbols are better than strings in term of memory and execution +1 for the answer – swapnesh Mar 12 '13 at 04:53
3

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}
2

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 
josliber
  • 43,891
  • 12
  • 98
  • 133
pinkninja
  • 109
  • 1
  • 7