Missing curly brackets for a hash in an array

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

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

seem identical:

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

I knew that such a deviation is possible for the method arguments, but I did not notice that this is possible for the array. Do I understand this rule correctly? And, is it described somewhere?

+7
source share
2 answers

It would seem that this is a new feature 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 > 
+4
source

I think that brackets (and without brackets, for example below) are called hash literals, and ruby ​​just tries to fit it as an element of an array.

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

But there are no rules, I think you cannot do this:

 >> [1, 2, c: 'd', e: 'f', 5] # syntax error, unexpected `]` (waiting for => or :) 
-one
source

All Articles