Is there a way to access method arguments in Ruby?

后端 未结 11 1098
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 17:00

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 f         


        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 17:59

    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 }

提交回复
热议问题