开发者

How do I deep copy a Proc in Ruby?

开发者 https://www.devze.com 2023-01-27 21:08 出处:网络
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:

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 clone would work on Procs, it wouldn't help you, because you'd still be calling clone on 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 @foo in a local variable that the lambda can close over.

Example:

def augment_foo()
  old_foo = @foo
  @foo = lambda { |x| x > 1 ? x*x : old_foo[x] }
end

This way old_foo will refer to the value that @foo had when augment_foo was called and everything will work as you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号