From: Brian Candler Date: 2010-09-22T04:38:21+09:00 Subject: Re: temporarily override instance variable in a block Jean-denis Vauguet wrote: > Two approach are illustrated: variable swapping and instance_eval. The > former does the trick but it's cumbersome and not thread-safe. The > latter, I don't understand why, fails, for the block seems to be called > in the > > If anyone can help with this, thanks in advance! There is no general solution to this. It will depend on the actual problem you're trying to solve. You're right that replacing the instance variable is not thread-safe. (Note that you should use begin .. ensure .. end to make sure the variable is put back even in the case of an exception) The self.class.new (or dup/clone) approach won't work for all objects. Some objects have compulsory arguments to their constructors, or have all sorts of side effects in their 'initialize' methods. The nearest you're likely to get is: o = self.class.allocate instance_variables.each do |v| o.instance_variable_set(v, instance_variable_get(v)) end But this almost certainly means you're thinking about the problem the wrong way. Try a more functional approach: pass the proxy as an argument, instead of looking at the @proxy instance variable. Or use the instance variable as the default. def whatever(proxy = @proxy) .. do something with proxy .. end -- Posted via http://www.ruby-forum.com/.