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

前端 未结 2 581
旧时难觅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条回答
  •  猫巷女王i
    2021-02-18 20:42

    You can use arity

    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.

    Example from ruby-doc

    class C
      def one;    end
      def two(a); end
      def three(*a);  end
      def four(a, b); end
      def five(a, b, *c);    end
      def six(a, b, *c, &d); end
    end
    
    c = C.new
    c.method(:one).arity     #=> 0 
    c.method(:two).arity     #=> 1
    c.method(:three).arity   #=> -1
    c.method(:four).arity    #=> 2
    c.method(:five).arity    #=> -3
    c.method(:six).arity     #=> -3
    

提交回复
热议问题