Pregunta

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?

¿Fue útil?

Solución

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' )

Otros consejos

Ruby 2.0 provides no built-in way to get a Hash from keyword arguments.

You must choose between:

  1. Using keyword arguments (as you currently are) and creating a Hash from those values separately, OR...

  2. Using a Hash argument with default values, such as the Ruby v1.9.3 strategies described here.

You could do write your method as 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}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top