有没有办法知道一个方法需要多少个参数? [英] Is there a way to know how many parameters are needed for a method?

查看:44
本文介绍了有没有办法知道一个方法需要多少个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用irb,我们可以通过执行以下操作列出特定对象的方法:

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

"Name".methods

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

But if I want to know how many parameters are needed for a particular method, how can I achieve this? I mean is there any way (by hitting some command on irb), we can get number of parameters for particular method (instead of referring to docs)?

.methods 只返回方法名,不返回方法的参数列表.

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

推荐答案

您可以使用方法 Method#arity:

You can use the method Method#arity:

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

来自 Ruby 文档:

From the Ruby documentation:

返回方法接受的参数数量的指示.为采用固定数量的方法返回一个非负整数论据.对于采用可变数量参数的 Ruby 方法,返回 -n-1,其中 n 是所需参数的数量.对于方法用 C 编写,如果调用采用可变数量的参数.

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,它可能非常有用:


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]] 

这篇关于有没有办法知道一个方法需要多少个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆