4

I am new to Ruby, and just came across this code snippet:

rr = {
  id: 215043,
  :'Official Name' => "Google, Inc."
}

What bugs be the most is this :'Official Name' =>. It looks like a symbol with spaces.

And when I print it, I see:

{:id=>"215043", :"Official Name"=>"Google, Inc."}

Please help me understand this.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Hairi
  • 3,318
  • 2
  • 29
  • 68
  • 1
    Consider: `"cat".to_sym #=> :cat`, `"cat 9 lives".to_sym #=> :"cat 9 lives"`, `"9lives".to_sym #=> :"9lives"`. What can you deduce from these results? – Cary Swoveland Jul 09 '19 at 17:44

2 Answers2

5

What bugs be the most is this :'Official Name' =>. It looks like a symbol with white spaces.

That's exactly what it is.

p :'Official Name'.class
# => Symbol

However, in a Hash literal you can put the colon at the end instead, which I think reads a little nicer:

rr = {
  id: 215043,
  "Official Name": "Google, Inc.",
}

rr.keys.each {|key| p [key, key.class] }
# => [:id, Symbol]
#    [:"Official Name", Symbol]

For future reference, the official docs are fairly easy to navigate once you get used to them. In this case, you'll want to follow the link for doc/syntax/literals.rdoc, then check out the sections on Symbols and Hashes.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
1

This is still a symbol.

Ruby lets you define a symbol that has spaces in it if you wrap it in quotes like that.

Check out this answer to see an example of a symbol with spaces being created from a String.

Piccolo
  • 1,612
  • 4
  • 22
  • 38