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

1

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.

Pasadis answered 18/1, 2011 at 7:59 Comment(2)
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.Groggy
I don’t always find a bug in the language itself, but when I do I’m using Ruby.Rightism
I
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

Instrument answered 18/1, 2011 at 18:16 Comment(1)
It's fixed in Ruby 1.9, so I think it WAS a bug :)Gelatinoid

© 2022 - 2024 — McMap. All rights reserved.