Ruby - Keyword Arguments - Can you treat all of the keyword arguments as a hash? How?

后端 未结 5 854
借酒劲吻你
借酒劲吻你 2020-12-15 16:51

I have a method that looks like this:

def method(:name => nil, :color => nil, shoe_size => nil) 
  SomeOtherObject.some_other_method(THE HASH THAT          


        
5条回答
  •  一生所求
    2020-12-15 17:19

    @Dennis 's answer is useful and educational. However, I noticed that Binding#local_variables will return all the local variables, regardless of when local_variables is executed:

    def locals_from_binding(binding_:)
      binding_.local_variables.map { |var|
        [var, binding_.local_variable_get(var)]
      }.to_h
    end
    
    def m(a:, b:, c:)
      args = locals_from_binding(binding_: binding)
      pp args
    
      d = 4
    end
    
    m(a: 1, b: 3, c: 5)
    # Prints:
    #   {:a=>1, :b=>3, :c=>5, :args=>nil, :d=>nil}
    # Note the presence of :d
    

    I propose a hybrid solution:

    def method_args_from_parameters(binding_:)
      method(caller_locations[0].label)
      .parameters.map(&:last)
      .map { |var|
        [var, binding_.local_variable_get(var)]
      }.to_h
    end
    
    def m(a:, b:, c:)
      args = method_args_from_parameters(binding_: binding)
      pp args
    
      d = 4
    end
    
    m(a: 1, b: 3, c: 5)
    # Prints:
    #   {:a=>1, :b=>3, :c=>5}
    # Note the absence of :d
    

提交回复
热议问题