省略数组中散列的花括号 [英] Omission of curly braces for a hash in an array

查看:34
本文介绍了省略数组中散列的花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到如果散列是数组中的最后一个元素,则可以省略散列的花括号.例如,表单:

I realized that the curly braces for a hash can be omitted if it is the last element in an array. For example, the forms:

[1, 2, 3, :a => 'A', :b => 'B']
[1, 2, 3, a: 'A', b: 'B']

似乎与以下内容相同:

[1, 2, 3, {:a => 'A', :b => 'B'}]
[1, 2, 3, {a: 'A', b: 'B'}]

我知道方法的参数可能会出现这种省略,但没有注意到数组可能会出现这种情况.我对这条规则的理解是否正确?而且,这是在某处描述的吗?

I knew this kind of omission is possible for arguments of a method, but had not noted it is possible for an array. Is my understanding of this rule correct? And, is this described somewhere?

推荐答案

这似乎是 1.9 的一个新特性:

This would seem to be a new feature of 1.9:

$ rvm use 1.8.7
$ irb
ruby-1.8.7-p352 :001 > x = [ 1,2,3,:a => 4, :b => 5 ]
SyntaxError: compile error
(irb):1: syntax error, unexpected tASSOC, expecting ']'
x = [ 1,2,3,:a => 4, :b => 5 ]
                 ^
  from (irb):1
ruby-1.8.7-p352 :002 > exit
$ rvm use 1.9.3
$ irb
ruby-1.9.3-p0 :001 > x = [ 1,2,3,:a => 4, :b => 5 ]
 => [1, 2, 3, {:a=>4, :b=>5}] 
ruby-1.9.3-p0 :002 >

这篇关于省略数组中散列的花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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