为什么这个代码没有编译在ruby 1.9上但是在ruby 1.8上?

时间:2021-12-23 15:59:40

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.

我想知道为什么这段代码工作是Ruby的版本之一,但不是两者兼而有之。

1 个解决方案

#1


5  

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.

虽然Ruby 1.9对于列表和类似列表的表示中的逗号比以前的版本更加宽松,但是在某些新的场合会出现语法错误。这似乎是一个。 Ruby 1.9严格地将其视为方法定义,并且不允许使用该逗号。

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.

您似乎也遇到了Ruby 1.8.7中已经纠正的边缘案例错误。列表扩展方法似乎不仅适用于一个项目。

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

#1


5  

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.

虽然Ruby 1.9对于列表和类似列表的表示中的逗号比以前的版本更加宽松,但是在某些新的场合会出现语法错误。这似乎是一个。 Ruby 1.9严格地将其视为方法定义,并且不允许使用该逗号。

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.

您似乎也遇到了Ruby 1.8.7中已经纠正的边缘案例错误。列表扩展方法似乎不仅适用于一个项目。

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