为什么我不能使用新的Ruby 1.9.2哈希语法使用整数作为键? [英] Why can't I use an integer as a key using the new Ruby 1.9.2 hash syntax?
问题描述
Ruby 1.9.2中的新哈希语法意味着我可以执行以下操作:
The new hash syntax in Ruby 1.9.2 means that I can do the following:
my_hash = {a: 1, b: 2, c: 3}
...相当于:
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?
推荐答案
仅适用于Ruby'符号',并且是常见用法的替代:
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 1.9.2哈希语法使用整数作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!