From: Robert Klemme Date: 2010-09-23T00:41:02+09:00 Subject: Re: temporarily override instance variable in a block On Tue, Sep 21, 2010 at 7:06 PM, Jean-denis Vauguet wrote: > I strived to override instance variable on a per-block basis, but I'm > not satisfied with my results. Here's a snippet: > http://gist.github.com/589924 > > The goal is: execute a block but have it use a different value for a > previously defined instance variable, all of this in the context of a > class instance (the instance variable belongs to this class instance). > > Two approach are illustrated: variable swapping and instance_eval. The > former does the trick but it's cumbersome and not thread-safe. Exchanging instance variable values is _never_ thread safe - unless you take extra measures (synchronization). > The latter, I don't understand why, fails, for the block seems to be called > in the ? Your second approach does not actually swap values of an instance variable but tries to create a copy of the instance and work with that. This has vastly different properties (apart from that it may not work for certain types of objects as Brian said): in cases you risk losing modifications on the copy. I completely agree with Brian: please provide more background. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/