From: "David A. Black" Date: 2003-12-09T22:11:13+09:00 Subject: Re: Adjusting the Scope of Blocks Hi -- On Tue, 9 Dec 2003, Robert Klemme wrote: > > "Gavin Sinclair" schrieb im Newsbeitrag > news:49755.203.185.214.34.1070949030.squirrel@webmail.imagineis.com... > > [Mark Cox wrote:] > > > > Hi, > > > > > > Is there a way to give a block associated with a method call the same > > > scope as if it were executing inside the method. > > > > > I've never done it myself, but you might try: > > > > class Foo > > def input_flags(&block) > > @FLAG_SEL = INPUT > > instance_eval &block > > end > > end > > > This works as expected. Note however that with this approach method local > variables are not accessible. We had an interesting discussion about this technique (instance_eval'ing closures) on irc last night. What emerged seemed to be that the effect of instance_eval is not, strictly speaking, to execute the block in current scope, but rather to execute it with the current 'self' as 'self'. I don't know if there's a term for that as concise as 'scope'; all I can think of is 'that thing where instance_eval temporarily changes "self"'.... I had never noticed that closures behave this way when instance_eval'd. My initial reaction is dislike. To me it feels too close to having the code in the block interpreted as an eval string. class C def m(&b) instance_eval(&b) instance_eval("n") end def n puts "This is the other #n" end end def n puts "This is an #n in the block's scope" end l = lambda { n } l.call C.new.m &l => This is an #n in the block's scope This is the other #n This is the other #n It feels non-closure-like to me. I don't see why a block should care what 'self' is at the time it's called; I thought the point was for it to preserve the context of its creation. David -- David A. Black dblack@wobblini.net