From: Robert Klemme Date: 2006-02-17T06:24:20+09:00 Subject: Re: recontextualizing a block (looking for deep magic) 2006/2/16, Phil Tomson : > What I'm trying to do probably isn't possible, but maybe someone knows some > deep magic. > > I'd like something like: > > def runit &b > a = 42 > pnew = Proc.new &b, binding > pnew.call > end > > runit { puts "a is: #{a}" } > > #would print: > a is: 42 > > Or course, Proc.new currently doesn't take a Binding object second argument. > What I'm wondering is if there is any way to 'rebind' or 'recontextualize' a > block? There is one way: you can use instance_eval with a block. This essentially just rebinds self but this is good enough often. Your example (even if the rebinding part worked) would likely suffer from a different problem: a is not known as local variable in the block so the compilation would probably not create code that reads the local variable a. Often there are alternative approaches, such as providing an argument to the block that makes certain data accessible. If you have a use case in mind I'd be glad to try to come up with more suggestions. Kind regards robert -- Have a look: http://www.flickr.com/photos/fussel-foto/