开发者

How do i get the names or arguments inside the method definition? [duplicate]

This question already has answers here: How to get argument names using reflection 开发者_开发知识库 (5 answers) Is there a way to return a method parameter names in ruby [duplicate] (4 answers) Closed 9 years ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜