Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

For instance:

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 wanted array.

I would like to know why this piece of code is working is either one of the Ruby's version but not both.

like image 953
oldergod Avatar asked Nov 30 '12 05:11

oldergod


1 Answers

While generally Ruby 1.9 is a lot more lenient about trailing commas in lists and list-like representations than previous versions, there are some new occasions where it will throw a syntax error. This seems to be one. Ruby 1.9 treats this as strictly as a method definition and won't allow that stray comma.

You've also seem to run up against an edge-case bug in Ruby 1.8.7 that has been corrected. The list expansion method doesn't seem to work with only one item.

A quick fix in this case might be:

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

In this case _ functions as a whatever variable.

In both versions you should get:

[[11, 1], [22, 2], [33, 3]]
like image 53
tadman Avatar answered Nov 01 '22 12:11

tadman