How do i get the names or arguments inside the method definition? [duplicate]
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
?
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")
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
Found the answer!
def speak (name, age, address)
puts local_variables
end
精彩评论