加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 有没有办法知道一个方法需要多少个参数?

发布时间:2020-12-16 21:43:26 所属栏目:百科 来源:网络整理
导读:使用irb,我们可以通过执行以下操作列出特定对象的方法: "Name".methods 但是,如果我想知道特定方法需要多少参数,那么我该如何实现呢?我的意思是有什么办法(通过在irb上打一些命令),我们可以获得特定方法的参数数量(而不是引用文档)? .methods只返回方法名
使用irb,我们可以通过执行以下操作列出特定对象的方法:
"Name".methods

但是,如果我想知道特定方法需要多少参数,那么我该如何实现呢?我的意思是有什么办法(通过在irb上打一些命令),我们可以获得特定方法的参数数量(而不是引用文档)?

.methods只返回方法名称,而不是方法参数列表.

解决方法

您可以使用方法 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]]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读