Is there a way to access method arguments in Ruby?

后端 未结 11 1074
没有蜡笔的小新
没有蜡笔的小新 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:55

    This may be helpful...

      def foo(x, y)
        args(binding)
      end
    
      def args(callers_binding)
        callers_name = caller[0][/`.*'/][1..-2]
        parameters = method(callers_name).parameters
        parameters.map { |_, arg_name|
          callers_binding.local_variable_get(arg_name)
        }    
      end
    
    0 讨论(0)
  • 2020-11-29 17:58

    One way to handle this is:

    def foo(*args)
        first_name, last_name, age, sex, is_plumber = *args
        # some code
        # error happens here
        logger.error "Method has failed, here are all method arguments #{args.inspect}"    
    end
    
    0 讨论(0)
  • 2020-11-29 17:58

    If you would change the method signature, you can do something like this:

    def foo(*args)
      # some code
      # error happens here
      logger.error "Method has failed, here are all method arguments #{args}"    
    end
    

    Or:

    def foo(opts={})
      # some code
      # error happens here
      logger.error "Method has failed, here are all method arguments #{opts.values}"    
    end
    

    In this case, interpolated args or opts.values will be an array, but you can join if on comma. Cheers

    0 讨论(0)
  • 2020-11-29 17:58

    It seems like what this question is trying to accomplish could be done with a gem I just released, https://github.com/ericbeland/exception_details. It will list local variables and vlaues (and instance variables) from rescued exceptions. Might be worth a look...

    0 讨论(0)
  • 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 }

    0 讨论(0)
提交回复
热议问题