Question

With proc and method, I get the following different results. Why is that?

proc {|x|}.arity                    # => 1 
proc {|x=1|}.arity                  # => 0 
def foo(x=1);end;method(:foo).arity # => -1 
Was it helpful?

Solution

Be careful of the fact that in ruby, Method and Proc are two different things.

For Proc#arity, the number returned is the number of arguments that would not be ignored by calling the proc.
For the first proc you declared, it takes exactly one argument, therefore it has an arity of 1. For your second proc, it has only one argument that is optional, therefore it really does not expect an argument at all, so it is 0.

For Method#arity, the number returned is the number of arguments accepted by the method.
Your method actually expects a variable number of arguments, namely 0..1, therefore arity is expected to return a negative number, here -1, because there is 0 required argument, and the formula is -n-1 (n being the number of required arguments).

Note that the documentation for the Proc#arity is misleading because it mentions the same formula as for Method#arity, while it is not true.

The case of lambdas is also interesting, because:

lambda {|x=1|}.arity     # => -1

It behaves like a Method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top