0

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.

Iván Cortés
  • 581
  • 1
  • 9
  • 22
  • What is the `class=` method used in `a.class = b.class`? – sawa Apr 04 '16 at 02:57
  • sorry, I ment, the boolean validation between both object class is true. – Iván Cortés Apr 04 '16 at 03:13
  • 1
    Possible duplicate of [In Ruby what is the meaning of colon after identifier in a Hash?](http://stackoverflow.com/questions/10645668/in-ruby-what-is-the-meaning-of-colon-after-identifier-in-a-hash) – SwiftMango Apr 04 '16 at 03:37

3 Answers3

2

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.

Petr Gazarov
  • 3,602
  • 2
  • 20
  • 37
2

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 }
spickermann
  • 100,941
  • 9
  • 101
  • 131
cozyconemotel
  • 1,121
  • 2
  • 10
  • 22
0

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.

Community
  • 1
  • 1
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160