Search code examples
ruby-on-railsruby

Is there a way to access method arguments in Ruby?


New to Ruby and ROR and loving it each day, so here is my question since I have not idea how to google it (and I have tried :) )

we have method

def foo(first_name, last_name, age, sex, is_plumber)
    # some code
    # error happens here
    logger.error "Method has failed, here are all method arguments #{SOMETHING}"    
end

So what I am looking for way to get all arguments passed to method, without listing each one. Since this is Ruby I assume there is a way :) if it was java I would just list them :)

Output would be:

Method has failed, here are all method arguments {"Mario", "Super", 40, true, true}

Solution

  • In Ruby 1.9.2 and later you can use the parameters method on a method to get the list of parameters for that method. This will return a list of pairs indicating the name of the parameter and whether it is required.

    e.g.

    If you do

    def foo(x, y)
    end
    

    then

    method(:foo).parameters # => [[:req, :x], [:req, :y]]
    

    You can use the special variable __method__ to get the name of the current method. So within a method the names of its parameters can be obtained via

    args = method(__method__).parameters.map { |arg| arg[1].to_s }
    

    You could then display the name and value of each parameter with

    logger.error "Method failed with " + args.map { |arg| "#{arg} = #{eval arg}" }.join(', ')
    

    Note: since this answer was originally written, in current versions of Ruby eval can no longer be called with a symbol. To address this, an explicit to_s has been added when building the list of parameter names i.e. parameters.map { |arg| arg[1].to_s }