ruby - Is there a way to know how many parameters are needed for a method? -


using irb, can list methods particular object doing following:

"name".methods 

but if want know how many parameters needed particular method, how can achieve this? mean there way (by hitting command on irb), can number of parameters particular method (instead of referring docs)?

.methods returns method names, not list of parameters method.

you can use method method#arity:

"string".method(:strip).arity # => 0 

from ruby documentation:

returns indication of number of arguments accepted method. returns nonnegative integer methods take fixed number of arguments. ruby methods take variable number of arguments, returns -n-1, n number of required arguments. methods written in c, returns -1 if call takes variable number of arguments.

so, example:

# variable number of arguments, 1 required def foo(a, *b); end method(:foo).arity # => -2  # variable number of arguments, none required def bar(*a); end method(:bar).arity # => -1  # accepts no argument, implemented in c "0".method(:to_f).arity # => 0  # variable number of arguments (0 or 1), implemented in c "0".method(:to_i).arity # => -1 


update i've discovered exitence of method#parameters, quite useful:

def foo(a, *b); end method(:foo).parameters # => [[:req, :a], [:rest, :b]]  

Comments