Is { 'symbol name': 5 }
and { "symbol name": 5 }
valid and well-defined Ruby 2 syntax for Hashes?
In Ruby 2, the following Hash literal notations are equivalent:
{ :my_key => 5 }
{ my_key: 5 }
{ :'my_key' => 5 }
{ :"my_key" => 5 }
The first two notations are documented on the Core API page for Hash
. The fourth notation is just plugging in an alternate Symbol literal notation (which is documented in the Core API page for Symbol
) to the first Hash notation, so it isn't really a different notation for Hash literals. Same goes for the third notation. That the single-quoted-string Symbol literal notation isn't mentioned on the Symbol
Core API page doesn't bother me too much, as it seems to work just like I'd expect.
But recently I noticed the following notations work too, and are also equivalent to the ones above:
{ "my_key": 5 }
{ 'my_key': 5 }
While it is kinda consistent (and works like I'd have expected, had I expected this to be valid at all) and probably useful, I find this remarkable enough to be a bit surprised. I couldn't find any documentation on this syntax, and this syntax isn't just constructed by plugging documented notations into other documented notations like the third and fourth notations above. (It's more like 'merging' the second with the third or fourth notation.) Thus I wondered:
Is this this just my Ruby interpreter (MRI ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]
) being nice about an undefined syntax, or is this a behavior I can expect from any complying Ruby 2 implementation?
(Not sure whether this question makes sense, if it is as Brian Shirai claims that "Ruby Is What [MRI] Does".)
{ :my_key => "my value" }
{ my_key: "my value" }
{ :'my_key' => "my value" }
{ :"my_key" => "my value" }
None of the above lines uses 2.x-only syntax. They are all also valid 1.9 syntax. (See demonstration.)
{ "my_key": "my value" }
{ 'my_key': "my value" }
That's feature request #4276 which landed in 2.2. That means it's invalid syntax in 2.1 or even older versions. It also means that an implementation that claims to implement 2.2 has to support it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With