Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use an integer as a key using the new Ruby 1.9.2 hash syntax?

Tags:

ruby

hash

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?

like image 867
Scott Avatar asked Nov 25 '10 22:11

Scott


People also ask

Can a Ruby hash key be an integer?

Integers are objects in Ruby, so are Hashes for that matter so you could use Hashes as keys.

Can a hash key be a number?

Hash key may refer to: Number sign, also known as the number, pound or hash key, a key on a telephone keypad.

How do I get the key value in Ruby?

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.

What does hash new do in Ruby?

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.


1 Answers

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).

like image 156
Peter Avatar answered Oct 11 '22 03:10

Peter