Reputation: 652
I have this:
a = {'x' => 3}
b = {'x': 3}
c = {x: 3}
d = {:x => 3}
e = {:'x' => 3}
So, I have that b = c = d = e = {:x => 3}
, meanwhile a = {"x" => 3}
but a.class == b.class
.
I don't understand what the difference is between a
and the rest of variables.
Upvotes: 0
Views: 91
Reputation: 1161
In b
,c
,d
, and e
, the key is a Symbol
.
In a
, the key is a String
.
a = { 'x' => 3 } #=> { "x" => 3 }
b = { 'x': 3 } #=> { :x => 3 }
c = { x: 3 } #=> { :x => 3 }
d = { :x => 3 } #=> { :x => 3 }
e = { :'x' => 3 } #=> { :x => 3 }
Upvotes: 2
Reputation: 121000
There is a significant difference between String
and Symbol
classes in ruby:
By convention, all but the very first hash notations cast keys to the Symbol
instance, while the first one uses the key (String
instance in this particular case) as is. (To be more precise: b
and c
cast key to the Symbol
instance, d
and e
do not cast anything, but keys given in these cases are Symbol
instances already.)
Since ('x' == :x) == false
, a
hash differs from the latters.
Upvotes: 0
Reputation: 3821
Your variable a
hash has "x"
key as a string, while other variables have that key as symbol.
Calling class
on an object in Ruby returns its class, in your example it is Hash
. In other words, the constructor of all hash instances, such as {x: 3}
is Hash
object.
Upvotes: 2