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).
-
1It's called a "hashrocket": http://stackoverflow.com/questions/4663074/in-ruby-what-does-mean-and-how-does-it-work – August Dec 29 '14 at 22:54
-
:this => :that is called hashrockets and are superior in every way... – John Naegle Dec 29 '14 at 22:55
-
Thanks for the answer! But this post doesn't seem to explain the difference between hashrockets and the other syntax. – Raynor Kuang Dec 29 '14 at 22:56
3 Answers
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

- 12,410
- 3
- 35
- 51
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"}

- 1,937
- 2
- 15
- 23
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.

- 1
- 1

- 12,923
- 3
- 46
- 74