开发者

Is this a bug in Method#to_proc? (Ruby 1.8.7)

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 (ir开发者_Go百科b):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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜