Is there a way to access method arguments in Ruby?

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

    Since Ruby 2.1 you can use binding.local_variable_get to read value of any local variable, including method parameters (arguments). Thanks to that you can improve the accepted answer to avoid evil eval.

    def foo(x, y)
      method(__method__).parameters.map do |_, name|
        binding.local_variable_get(name)
      end
    end
    
    foo(1, 2)  # => 1, 2
    

提交回复
热议问题