为什么我不能使用新的 Ruby 1.9.2 哈希语法将整数用作键? [英] Why can't I use an integer as a key using the new Ruby 1.9.2 hash syntax?

查看:26
本文介绍了为什么我不能使用新的 Ruby 1.9.2 哈希语法将整数用作键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 'symbols',并且是常见用法的替代:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆