Is there a way to access method arguments in Ruby? -
new ruby , ror , loving each day, here question since have not idea how google (and have tried :) )
we have method
def foo(first_name, last_name, age, sex, is_plumber) # code # error happens here logger.error "method has failed, here method arguments #{something}" end
so looking way arguments passed method, without listing each one. since ruby assume there way :) if java list them :)
output be:
method has failed, here method arguments {"mario", "super", 40, true, true}
in ruby 1.9.2 , later can use parameters
method on method list of parameters method. return list of pairs indicating name of parameter , whether required.
e.g.
if do
def foo(x, y) end
then
method(:foo).parameters # => [[:req, :x], [:req, :y]]
you can use special variable __method__
name of current method. within method names of parameters can obtained via
args = method(__method__).parameters.map { |arg| arg[1].to_s }
you display name , value of each parameter with
logger.error "method failed " + args.map { |arg| "#{arg} = #{eval arg}" }.join(', ')
note: since answer written, in current versions of ruby eval
can no longer called symbol. address this, explicit to_s
has been added when building list of parameter names i.e. parameters.map { |arg| arg[1].to_s }
Comments
Post a Comment