Omission of curly braces for a hash in an array

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']

seem to be identical to:

[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的新功能:

$ 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 >

I think the brackets (and no brackets, like below) are called hash literals and ruby just tries to fit it as an array element.

>> [1, 2, c: 'd', e: 'f'] # ruby 1.9 hash literals
=> [1, 2, {:c=>"d", :e=>"f"}]

But there aren't more rules to it, I think - you can't do this:

>> [1, 2, c: 'd', e: 'f', 5] # syntax error, unexpected `]` (waiting for => or :)
链接地址: http://www.djcxy.com/p/10472.html

上一篇: MySql连接器/ Net当前源(截至二月

下一篇: 在数组中省略大括号的大括号