Is there a way to access method arguments in Ruby?

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

    If you need arguments as a Hash, and you don't want to pollute method's body with tricky extraction of parameters, use this:

    def mymethod(firstarg, kw_arg1:, kw_arg2: :default)
      args = MethodArguments.(binding) # All arguments are in `args` hash now
      ...
    end
    

    Just add this class to your project:

    class MethodArguments
      def self.call(ext_binding)
        raise ArgumentError, "Binding expected, #{ext_binding.class.name} given" unless ext_binding.is_a?(Binding)
        method_name = ext_binding.eval("__method__")
        ext_binding.receiver.method(method_name).parameters.map do |_, name|
          [name, ext_binding.local_variable_get(name)]
        end.to_h
      end
    end
    

提交回复
热议问题