Reputation: 3715
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.
Upvotes: 4
Views: 180
Reputation: 106027
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.
Upvotes: 5
Reputation: 1666
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.
Upvotes: 1