Why is this code not compiling on ruby ​​1.9, but on ruby ​​1.8?

Sorry for the title, I don't know how this syntax is called.

For example:

ary = [ [11, [1]], [22, [2, 2]], [33, [3, 3, 3]] ] # want to get [ [11, 1], [22, 2], [33, 3] ] 

Ruby 1.8

 ary.map{|x, (y,)| [x, y] } #=> [[11, 1], [22, 2], [33, 3]] ary.map{|x, (y)| [x, y] } #Syntax error, unexpected '|', expecting tCOLON2 or '[' or '.' #ary.map{|x, (y)| [x, y] } # ^ 

Ruby 1.9

 ary.map{|x, (y,)| [x, y] } #SyntaxError: (irb):95: syntax error, unexpected ')' #ary.map{|x, (y,)| [x, y] } # ^ ary.map{|x, (y)| [x, y] } #=> [[11, 1], [22, 2], [33, 3]] 

※ I am not asking for a way to get the desired array.

I would like to know why this piece of code works, or is one of the Ruby versions, but not two .

+7
source share
1 answer

While overall Ruby 1.9 is much more lenient about trailing commas in lists and views like lists than previous versions, there are a few new cases where it will generate a syntax error. It seems to be one thing. Ruby 1.9 sees this as a strict definition of a method and does not allow this wandering comma.

You also seem to have encountered a marginal case error in Ruby 1.8.7 that has been fixed. The list expansion method does not seem to work with just one item.

A quick fix in this case could be:

 ary.map{|x, (y,_)| [x, y] } 

In this case, _ functions like any variable.

In both versions you should get:

 [[11, 1], [22, 2], [33, 3]] 
+5
source

All Articles