0

Is there a way to get a list of the argument names in a method?

For example, suppose I have the following method definition:

def speak(name, age, address)
  # some code
end

How can I get an array of name, age, and address?

wersimmon
  • 2,809
  • 3
  • 22
  • 35
denniss
  • 17,229
  • 26
  • 92
  • 141
  • This is a duplicate of [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 [Ruby: How to inspect the parameters of an instance method without creating a new instance?](http://StackOverflow.Com/q/6717912/#6717939). – Jörg W Mittag Aug 21 '11 at 10:14

3 Answers3

2

You can use the values directly.

def speak(name, age, address)
  puts "Hello #{name}!"
end

To access the names you could use local_variables but I don't really recommend it.

def speak(name, age, address)
  p local_variables # => [:name, :age, :address]
end

But most likely you'll want to use a hash:

def speak(hash)
   # use the keys/values of hash
end

Now you can use

speak({:name => "foo", :age => 42, :address => "123"})
# or
speak(:name => "foo", :age => 42, :address => "123")
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • I am talking about the argument's variable name. I know this might sound kind of stupid because I am already supposed to know the naem of the variables of the arguments. – denniss Aug 21 '11 at 06:57
  • So why can't you just use Hash as an argument to your method? Then you will be able to collect passed name-value pairs. Why not? – Daniel O'Hara Aug 21 '11 at 07:00
  • I know that using hash is the easiest way to go but I am just wondering whether it is possible to get the argument's variable names without using hash as the method argument. – denniss Aug 21 '11 at 07:03
  • @denniss: See edited answer again :) – jtbandes Aug 21 '11 at 07:05
1

You can use local_variables for it, but there is a better way:

def speak(name, age, address)
  p self.method(__method__).parameters #=> [[:req, :name], 
                                            [:req, :age], 
                                            [:req, :address]]
end

When you are using local_variables you should use it at the beginning of the method:

def speak(name, age, address)
  foo = 1
  p local_variables #=> [:name, :age, :address, :foo]
end
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
0

Found the answer!

def speak (name, age, address)
 puts local_variables
end
denniss
  • 17,229
  • 26
  • 92
  • 141