开发者

Is there a way to return a method parameter names in ruby [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Getting Argument Names In Ruby Reflection

Is it possible to get the parameter names of a method ?

Example with:

def method_called(arg1, arg2)
  puts my_method.inspect
end

I would like to know what method (my_method) should I call to get the following output:

开发者_高级运维
["arg1", "arg2"]


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.

For the format you want, try

method(:foo).parameters.map(&:last).map(&:to_s)
  # => ['a', 'b', 'c', 'd', 'e']


1

If you are on Ruby 1.9.1 you can use the MethoPara gem. This allows you to do the following:

def method_called(arg1, arg2)
  method(caller[0][/`([^']*)'/, 1].to_sym).parameters
end

2

You can use the approach proposed by Michael Grosser at his blog.

3

Merb Action Args


Within a method, you can get the names you've given the arguments by calling local_variables at the beginning (since no other local variables will have been defined at the time).

However, I don't think any good will come of this for any purpose besides maybe logging info. If you have a specific goal in mind, we could probably find something more idiomatic.


if you want the value for the default values, too, there's the "arguments" gem

$ gem install rdp-arguments
$ irb
>> require 'arguments'
>> require 'test.rb' # class A is defined here
>> Arguments.names(A, :go)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜