The new hash syntax in Ruby 1.9.2 means that I can do the following:
my_hash = {a: 1, b: 2, c: 3}
... which is equivalent to:
my_hash = {:a => 1, :b => 2, :c => 3}
Okay, so using the old syntax it's possible to do this (first key is an integer):
my_hash = {1 => 1, :b => 2, :c => 3}
And I've found it's even possible to mix the new and the old syntax like this:
my_hash = {1 => 1, b: 2, c: 3}
So, if we invoke the 'principle of least surprise', one would expect that the following would be legal:
my_hash = {1: 1, b: 2, c: 3}
... but it isn't. It generates a syntax error:
SyntaxError: (irb):40: syntax error, unexpected '='
my_hash = = {1: 1, b: 2, c: 3}
Can anybody explain if this is this a limitation of the parser, or are there very good reasons why this isn't possible, or allowed?
Integers are objects in Ruby, so are Hashes for that matter so you could use Hashes as keys.
Hash key may refer to: Number sign, also known as the number, pound or hash key, a key on a telephone keypad.
You can find a key that leads to a certain value with Hash#key . If you are using a Ruby earlier than 1.9, you can use Hash#index . Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera.
new : This method returns a empty hash. In the first form the access return nil. If obj is specified then, this object is used for all default values. If a block is specified, then it will be called by the hash key and objects and return the default value.
This syntax is only for Ruby 'symbols', and is an alternative to the common usage:
:symbol => 5
rather than as a general key. More on symbols here. And others have written about this with respect to the principal of least surprise (see here).
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