Search code examples
rubyrecursionnamed-parameterskeyword-argument

Is there a way to do recursion with keyword arguments in ruby 2 without re-specifying each argument?


Assume I have a method header:

def meth(a: val1, b: val2, c: val3)

and inside meth, I want to make a recursive call, and pass all the same arguments, but change one..

maybe something similar to this, semantically:

meth(_args_.merge(c: newval))

is this possible?


Solution

  • Not sure if a built-in method exists to do so, but it's evidently possible using local_variables and some eval-fu:

    def foo(bar: :baz)
      Hash[local_variables.map { |k| [k, eval("#{k}")] }]
    end
    
    foo # {:bar=>:baz}
    

    Related question:

    How do I dynamically create a local variable in Ruby?