I have a method that looks like this:
def method(:name => nil, :color => nil, shoe_size => nil)
SomeOtherObject.some_other_method(THE HASH THAT
@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