有没有办法在Ruby中返回方法参数名称 [英] Is there a way to return a method parameter names in ruby
本文介绍了有没有办法在Ruby中返回方法参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
在Ruby反射中获取参数名称
Possible Duplicate:
Getting Argument Names In Ruby Reflection
是否可以获取方法的参数名称?
Is it possible to get the parameter names of a method ?
示例:
def method_called(arg1, arg2)
puts my_method.inspect
end
我想知道应该调用哪种方法(my_method)以获取以下输出:
I would like to know what method (my_method) should I call to get the following output:
["arg1", "arg2"]
推荐答案
在Ruby 1.9.2中,您可以轻松获取任何Proc
的参数列表(因此当然也可以获取任何Method
或UnboundMethod
)与Proc#parameters
:
In Ruby 1.9.2, you can trivially get the parameter list of any Proc
(and thus of course also of any Method
or UnboundMethod
) with Proc#parameters
:
def foo(a, b=nil, *c, d, &e); end
p method(:foo).parameters
# => [[:req, :a], [:opt, :b], [:rest, :c], [:req, :d], [:block, :e]]
格式是由成对的符号组成的数组:类型(必需,可选,休止符,块)和名称.
The format is an array of pairs of symbols: type (required, optional, rest, block) and name.
尝试使用所需的格式
method(:foo).parameters.map(&:last).map(&:to_s)
# => ['a', 'b', 'c', 'd', 'e']
这篇关于有没有办法在Ruby中返回方法参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文