문제

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.

도움이 되었습니까?

해결책

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]]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top