Is there a straightforward way in Ruby to produce a copy of a Proc?
I have a Proc called @foo. I want another method to periodically augment @foo with additional logic. For example:
# create initial Proc
@foo = lambda { |x| x }
# augment with more logic
@foo = lambda { |x| x > 1 ? x*x : @foo[x] }
I don’t want the second line that does the augmentation to produce a recursive function. Instead, I want @foo to be bound by value into the lexical scope of the new @foo definition, producing a function that looks more like this:
@foo = lambda { |x| x > 1 ? x*x : lambda{ |x| x }[x] }
I get an infinite recursion and an eventual stack overflow instead, due to the resulting function looking like this:
@foo = lambda { |x| x > 1 ? x*x : lambda { |x| x > 1 ? x*x : { lambda |x| # etc...
I’d like the code to be like this:
# augment with more logic
@foo = lambda { |x| x > 1 ? x*x : (@foo.clone)[x] }
but clone doesn’t work on Procs.
Additionally, the standard Ruby deep copy hack, using marshal and unmarshal, doesn’t work on Procs either. Is there some way to do this?
Even if
clonewould work onProcs, it wouldn’t help you, because you’d still be callingcloneon the new value of@foo, not on the previous one like you want.What you can do instead is just store the old value of
@fooin a local variable that the lambda can close over.Example:
This way
old_foowill refer to the value that@foohad whenaugment_foowas called and everything will work as you want.