2

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?

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352
  • Could you make the argument a hash, merge it with a hash containing the defaults, do what you need to do in `meth`, then change the one key for the recursion? I understand something like that was done before named parameters were supported. – Cary Swoveland Jan 20 '14 at 23:14

1 Answers1

1

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?

Community
  • 1
  • 1
Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
  • local_variables is neat. Though, this method has quite a few non-formal arguments - so local_variables is quite big. Is there maybe a cleaner way to pass only what the method header has? I suppose one could do `method(:meth).parameters.map{|a| a.last}` and filter `local_variables` base on the result of that. At that point, it would be about as long as specifying all the parameters. lol. Still neat to know that this is possible though. – NullVoxPopuli Jan 20 '14 at 21:23
  • 1
    Null, if you did that, you might use `method(__method__).parameters...` instead. – Cary Swoveland Jan 20 '14 at 23:05