Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (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.

like image 691
Sam Stokes Avatar asked Jan 18 '11 07:01

Sam Stokes


1 Answers

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

like image 116
Conrad Irwin Avatar answered Oct 23 '22 05:10

Conrad Irwin