13

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.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Sam Stokes
  • 14,617
  • 7
  • 36
  • 33
  • 4
    Normally I'm skeptical when someone thinks they've found a bug in the language itself, but I see no other explanation for this behavior, especially considering that it works as expected in 1.9. Hopefully someone wiser can enlighten us, cause this has me pretty curious. – Jimmy Jan 18 '11 at 11:50
  • 1
    I don’t always find a bug in the language itself, but when I do I’m using Ruby. – Josh Lee Oct 05 '11 at 22:50

1 Answers1

13

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

Conrad Irwin
  • 1,312
  • 8
  • 13