作者:听天由命____497 | 来源:互联网 | 2023-02-04 20:44
Giventhefollowingmethodthattakesoneargument:给定以下方法,它只接受一个参数:deffoo(arg);parg;endIc
Given the following method that takes one argument:
给定以下方法,它只接受一个参数:
def foo(arg); p arg; end
I can call it with an empty array:
我可以用一个空数组来调用它:
foo([])
# prints []
I can also save it as a Method
object and call that with an empty array, with the same result:
我也可以将它保存为一个方法对象,并使用一个空数组调用它,得到相同的结果:
method(:foo).call([])
# prints []
However, if I convert the Method
object to a Proc
and call that with an empty array, I get an ArgumentError
:
但是,如果将方法对象转换为Proc,并使用空数组调用它,则会得到一个ArgumentError:
method(:foo).to_proc.call([])
# ArgumentError: wrong number of arguments (0 for 1)
# from (irb):4:in `foo'
# from (irb):4:in `to_proc'
# from (irb):10:in `call'
I expected it to behave the same as the previous two cases. Instead, it seems to be behaving as if I'd written foo(*[])
. However, if I call it with a non-empty array, it does behave the way I expected:
我希望它的行为与前两种情况相同。相反,它的行为好像我写了foo(*[])。但是,如果我用非空数组调用它,它的行为确实符合我的预期:
method(:foo).to_proc.call([1])
# prints [1]
So it destructures the argument, but only if the argument happens to be an empty array. And only if I call Method#to_proc
.
它会破坏参数,但前提是参数碰巧是空数组。如果我调用方法#to_proc。
Is there a gap in my understanding of how Method
or Proc
work, or is this a bug?
在我对方法或Proc工作方式的理解上是否存在差距,或者这是一个bug?
I'm running Ruby 1.8.7-p299. I observe the same behaviour in 1.8.6-p399 and 1.8.7-head. However, I don't see it in 1.9.1-p378: there all three forms print []
when called with an empty array.
我运行Ruby 1.8.7-p299。我在1.8.6-p399和1.8.7-head观察到同样的行为。但是,我在1.9.1-p378中没有看到:当使用空数组调用时,这三种表单都打印[]。
1 个解决方案