1

What the title says. I've been trying to google it, but it's a little difficult to phrase it so google knows what I'm looking for (especially since I don't know the terminology).

Raynor Kuang
  • 483
  • 3
  • 11

3 Answers3

4

When the key: value syntax is used in a Hash literal, the key always becomes a Symbol:

{foo: "bar"}.keys[0].class # => Symbol

When the key => value syntax is used, the key can be any type (including a Symbol):

{:foo => "bar"}.keys[0].class # => Symbol
{1 => "bar"}.keys[0].class    # => Fixnum
August
  • 12,410
  • 3
  • 35
  • 51
1

The "hashrocket" syntax => is used to match up any key value pair in a hash. The newer (and shorter) syntax for hash key value pairs : can only be used for symbol keys.

{foo: bar}

is equivalent to:

{:foo => bar}

Generally speaking if all the keys in your hash are (or should be) symbols then I would recommend the new syntax as it is shorter and reads more easily

{a: 1, b: 2}

However, if any of the keys are not symbols then I would recommend using the older, more flexible syntax:

{"what" => 3, :frequency => 4.43, kenneth => "Bob"}
Coenwulf
  • 1,937
  • 2
  • 15
  • 23
0

this: value is the newer syntax for hash literals from ruby 1.9.3 onwards.

:this => value is the older syntax; and is valid in newer versions of ruby as well.

Whats the benefit of the newer syntax?

Community
  • 1
  • 1
Prakash Murthy
  • 12,923
  • 3
  • 46
  • 74