How can I get named parameters into a Hash?

ruby, ruby-2.0, ruby-2.1

Solution

def my_method(required_param, named_param_1: nil, named_param_2: nil)
  named_params = method(__method__).parameters.each_with_object({}) do |p,h|
      h[p[1]] = eval(p[1].to_s) if p[0] == :key
  end
  p named_params # {:named_param_1=>"hello", :named_param_2=>"world"}

  # do something with the named params
end

my_method( 'foo', named_param_1: 'hello', named_param_2: 'world' )

Problem

I want to have named parameters to a method so the API is clear to the caller, but the implementation of the method needs the named parameters in a hash. So I have this: ``` def my_method(required_param, named_param_1: nil, named_param_2: nil) named_params = { named_param_1: named_param_1, named_param_2: named_param_2 } # do something with the named params end ``` This works, but I have to do this in quite a few places, and I would rather have some helper that dynamically gets the named parameters into a hash. I haven't been able to find a way to do this. Any thoughts on how to accomplish this?

Original source