How can I get named parameters in a hash?

I want to have named parameters for the method, so the API is clear to the caller, but to implement the method, you need named parameters in the 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 it in several places, and I would rather have a helper that dynamically gets named parameters to the hash. I could not find a way to do this. Any thoughts on how to do this?

+4
source share
3 answers
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' )
+4
source

Ruby 2.0 does not provide a built-in way to get Hash arguments from keywords.

You must choose between:

  • ( ) , OR...

  • Hash , Ruby v1.9.3 .

+1

You can write your method as shown below:

def my_method(required_param, named_param_1: nil, named_param_2: nil)
   named_params = Hash[method(__method__).parameters.select do |first,last| 
    [last,eval("#{last}")] if first == :key
  end]
end

my_method(12, named_param_1: 11,named_param_2: 12)
# => {:named_param_1=>11, :named_param_2=>12}
0
source

All Articles