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"]
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"]
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.
Somebody has posted the same question here is it:
http://stackoverflow.com/questions/622324/getting-argument-names-in-ruby-reflection
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
You can use the approach proposed by Michael Grosser at his blog.
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']
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)