views:

101

answers:

5

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"]
A: 

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.

Chuck
It's useful for loggin but it's for console usage. When I am in a irb session and I want to call a specific method that I don't remember tts parameters. I would like to have a easy way of knowing them without going to the source code or using ri.
Martinos
A: 

Somebody has posted the same question here is it:

http://stackoverflow.com/questions/622324/getting-argument-names-in-ruby-reflection

Martinos
A: 

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

KandadaBoggu
+5  A: 

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']
Jörg W Mittag
Good news that this exist for Ruby 1.9.2, I will take note of that. But for the moment I am using 1.8.7.
Martinos
A: 

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)
rogerdpack