Why can't I use an integer as a key using the

2019-01-19 11:05发布

问题:

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?

回答1:

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



标签: ruby hash