1

Is there a quick way to output the possible parameter names of a ruby method?

For example:

def my_method(param1, param2, param3, ...)
  # stuff
end

puts get_params("my_method")

which would output something like:

param1
param2
param3
...

Thanks!

Oh, btw I'm on ree-1.8.7...

ifightcrime
  • 1,216
  • 15
  • 18
  • 2
    possible duplicate of [Getting Argument Names In Ruby Reflection](http://stackoverflow.com/questions/622324/getting-argument-names-in-ruby-reflection) - the original question asks slightly more, but Jorg Mittag's answer answers your question. – Andrew Grimm Oct 03 '11 at 22:13
  • even the first response has some pretty helpful insight, thanks man – ifightcrime Oct 03 '11 at 23:17
  • There's a couple of other duplicates as well: [Is there a way to return a method parameter names in ruby](http://StackOverflow.Com/q/2452077/#2452322), [Reflection on method parameters in Ruby](http://StackOverflow.Com/q/3456827/#3460072), [Any ruby library to inspect what are the arguments that a certain methods take?](http://StackOverflow.Com/q/6420695/#6425175) and [How do i get the names or arguments inside the method definition?](http://StackOverflow.Com/q/7136868/). I guess it would be time to add some kind of search feature to StackOverflow, maybe a textbox in the top right corner? – Jörg W Mittag Oct 04 '11 at 00:34
  • Sorry, I should have edited my post earlier. I'm on ree-1.8.7 which doesn't have Method#parameters, as mentioned below. ;)I think I can get by with local_Variables, though not ideal. – ifightcrime Oct 04 '11 at 04:07

1 Answers1

4

How about:

class A
  def my_method(param1, param2, param3)
    # stuff
  end
end

A.instance_method(:my_method).parameters # => [[:req, :param1],[:req, :param2],[:req, :param3]]

A.instance_method(:my_method).parameters.collect { |p| p[1] } # => [:param1, param2, param3]

And if you do it on the irb console, as in your example:

>> def my_method(param1, param2, param3)
>>   # stuff
>> end
=> nil

>> def get_params(method_name)
>>   self.class.instance_method(method_name.to_sym).parameters.collect { |p| p[1] }.each { |name| puts name }
>> end
=> nil

>> get_params(:my_method)
param1
param2
param3
=> [:param1, :param2, :param3]

(Copy/pasted from my irb console.)

rdvdijk
  • 4,400
  • 26
  • 30
  • 1
    It should be know that whilst this is the best answer, Method#parameters is 1.9 only – Lee Jarvis Oct 03 '11 at 20:36
  • 1
    Exactly 1.9.2. Ruby 1.9.1 doesn't contain it (at least my version ;) ) – knut Oct 03 '11 at 20:38
  • I'm stuck using ree-1.8.7, which doesn't look like it has #parameters either. This is definitely a solution though, but is there a way without that method? – ifightcrime Oct 03 '11 at 22:42
  • +1 .. just re-read the question.. he is asking for the names of the params :) – Tilo Oct 03 '11 at 23:29