From: Eric Mahurin Date: 2005-06-08T01:27:20+09:00 Subject: Re: making a duck --- Robert Klemme wrote: > Eric Mahurin wrote: > > --- nobu.nokada@softhome.net wrote: > >> At Tue, 7 Jun 2005 11:59:47 +0900, > >> Eric Mahurin wrote in [ruby-talk:144750]: > >>> Is there an advantage to having a separate Behavior class > >> as > >>> opposed the solution I had: making a singleton Object > >> directly? > >> > >> To allow sharing same behavior. > > > > I'm not sure how much application this would have over the > > conventional class definition approach. > > > > At first I didn't think this would work because I thought > you > > wouldn't be able to create any instance variables using > > define_method. I thought any @ variables in a proc would > refer > > to the @ variable in the original context, but > define_method > > apparently rebinds them to the object. > > I always remind myself that the binding of "self" changes - > even for each > method invocation. This explains pretty good why this works > as it should. define_method, instance_eval, class_eval, module_eval, and maybe others seem to have this special ability - rebind the meaning of self (but not locals) for a Proc. This brings us back to the topic I talked about earlier - unbind/rebind procs. It would be nice if we could do the same thing to a Proc that these methods can do internally: aProc.rebind_self(obj) -> aNewProc # rebind what self is With this, "obj.instance_eval(&proc)" would be equivalent to "proc.rebind_self(obj).call". Other useful rebindings may be: aProc.rebind_locals(binding) -> aNewProc aProc.rebind_all(binding) -> aNewProc # replace local variables with their current values aProc.unbind_locals -> aNewProc BTW, I don't see the value that class_eval and module_eval provide over instance_eval. classes and modules can be treated like instances just like any other object. __________________________________ Discover Yahoo! Get on-the-go sports scores, stock quotes, news and more. Check it out! http://discover.yahoo.com/mobile.html