From: Mauricio Fernandez Date: 2006-07-10T23:13:46+09:00 Subject: Re: instance_exec On Mon, Jul 10, 2006 at 08:29:46PM +0900, transfire@gmail.com wrote: > > PS: I'm still curious about the reason for using a module. * it allows instance_exec to work on frozen objects and immediate values * it doesn't pollute Object with several methods (even if temporarily), only one module > I think the idea was to save frm creting a singleton class, but at the > expense of a module I don't see why either. Anyway, here the version I > put in Facets. Please evaluate. > > module Kernel > > # Like instace_eval but allows parameters to be passed. > # > # The implementation is thread-safe thanks to the > # Thread.current.object_id trick, but it doesn't work with > # immediate values (Fixnums and friends), and most > # importantly it bombs when given a frozen object. > def instance_exec(*args, &block) > mname = > "__instance_exec(#{Thread.current.object_id},#{caller.object_id})" > Object.class_eval{ define_method(mname, &block) } > begin > ret = send(mname, *args) > ensure > Object.class_eval{ undef_method(mname) } > end > ret > end > > end heh you copied the comment from my blog entry[1] but that's not the implementation it applied to ;). The above does work with immediate values and frozen objects. But I now consider it flawed nonetheless, read http://eigenclass.org/hiki.rb?bounded+space+instance_exec [1] http://eigenclass.org/hiki.rb?instance_exec -- Mauricio Fernandez - http://eigenclass.org - singular Ruby