这是 Method#to_proc 中的错误吗? (红宝石 1.8.7)
给定以下带有一个参数的方法:
def foo(arg); p arg; end
我可以使用空数组调用它:
foo([])
# prints []
我还可以将其保存为 Method
对象并使用空数组调用 that,相同的结果:
method(:foo).call([])
# prints []
但是,如果我将 Method
对象转换为 Proc
并使用空数组调用 that,我会得到一个 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'
我期望它的行为与前两种情况相同。相反,它的行为似乎就像我编写了 foo(*[])
一样。但是,如果我使用非-空数组调用它,它确实会按照我预期的方式运行:
method(:foo).to_proc.call([1])
# prints [1]
因此它会解构参数,但前提是该参数恰好是一个空数组。并且仅当我调用 Method#to_proc
时。
我对 Method
或 Proc
工作原理的理解是否存在差距,或者这是一个错误?
我正在运行 Ruby 1.8.7-p299。我在 1.8.6-p399 和 1.8.7-head 中观察到相同的行为。但是,我在 1.9.1-p378 中没有看到它:当使用空数组调用时,所有三种形式都会打印 []
。
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
:
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:
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
.
Is there a gap in my understanding of how Method
or Proc
work, or is this a 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这几乎肯定是一个错误,
我怀疑发生这种情况的原因是 Method#call 的 arity -1 (期望 C 参数数组),而 Proc#call 的 arity -2 (期望 Ruby 参数数组)。
在 eval.c 中 Proc#call 定义上方有一个进一步有用的注释,可以进一步阐明该问题:
/* CHECKME: 参数检查语义是否正确? */
也许我们应该将其更改为 FIXME :p
This is almost certainly a bug,
I suspect the reason this is happening is that Method#call has arity -1 (Expecting a C array of arguments), and Proc#call has arity -2 (Expecting a Ruby Array of arguments).
There's a further helpful comment in eval.c above the definition of Proc#call that may shed further light on the issue:
/* CHECKME: are the argument checking semantics correct? */
Maybe we should change that to a FIXME :p