使用irb,我们可以通过执行以下操作列出特定对象的方法:
"Name".methods
但是,如果我想知道特定方法需要多少参数,那么我该如何实现呢?我的意思是有什么办法(通过在irb上打一些命令),我们可以获得特定方法的参数数量(而不是引用文档)?
解决方法
您可以使用方法
Method#arity
:
"string".method(:strip).arity # => 0
从Ruby文档:
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.
所以,例如:
# 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
更新我刚刚发现了Method#parameters
的退出,这可能是非常有用的:
def foo(a,*b); end method(:foo).parameters # => [[:req,:a],[:rest,:b]]