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

前端 未结 2 570
旧时难觅i
旧时难觅i 2021-02-18 20:31

Using irb, we can list methods for particular object by doing following:

\"Name\".methods

But if I want to know how many parameter

2条回答
  •  渐次进展
    2021-02-18 20:57

    You can use the method Method#arity:

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

    From the Ruby documentation:

    Returns an indication of the number of arguments accepted by a method. Returns a nonnegative integer for methods that take a fixed number of arguments. For Ruby methods that take a variable number of arguments, returns -n-1, where n is the number of required arguments. For methods written in C, returns -1 if the call takes a variable number of arguments.

    So, for example:

    # Variable number of arguments, one is 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 just discovered the exitence of Method#parameters, it could be quite useful:

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

提交回复
热议问题