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

StackOverflow https://stackoverflow.com/questions/21243455

Вопрос

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?

Это было полезно?

Решение

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?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top