From: "Mauricio Fernández" Date: 2004-08-26T07:34:14+09:00 Subject: Re: *with* block? On Thu, Aug 26, 2004 at 06:56:13AM +0900, David A. Black wrote: > > There is an awkward work around. First write +with+ like this: > > > > module Kernel > > def with(obj, &block) > > obj.instance_eval { @self = eval("self", block) } > > obj.instance_eval &block > > end > > end > > [...] > You could also do: > > def testing_dog > s = self > t = Test.new > talk > with t do > test > s.talk > end > end > > (i.e., put the burden of providing a reference to self-the-Dog to on > the method, rather than on 'with') It also has the additional benefit of being thread-safe, or more precisely not as thread-unsafe :P Also, polluting the original object with another i.v. feels very wrong. You could also do batsman@tux-chan:/tmp$ cat fdgdfg.rb def with(obj, &block) o = Object.new s = self # I'd use define_method but {|*a,&b| ...} is 1.9 only o.instance_eval{ @self = s; @obj = obj } class << o def method_missing(meth,*a,&b) @obj.send(meth, *a, &b) end end o.instance_eval(&block) end class Foo def foo puts "Foo#foo" with(Bar.new){ bar; @self.babar{ puts "foo" } } end def babar puts "1931" yield end end class Bar; def bar; puts "Bar#bar" end end Foo.new.foo batsman@tux-chan:/tmp$ ruby fdgdfg.rb Foo#foo Bar#bar 1931 foo But I don't really like it. -- Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com