From: "T. Onoma" Date: 2003-11-30T09:52:26+09:00 Subject: Re: Controlled block variables On Sunday 30 November 2003 12:34 am, Pit Capitain wrote: > but couldn't because "a" wasn't visible, with define_method you can > instead write > > a = [1,2,3] > class_eval %{ > define_method :meth, proc{ > > } > } > > A silly example: > > def add_long_method_to_class( klass, a, h ) > klass.class_eval %{ > define_method :long_generated_method, proc{ > local_var = a.size > h[ "s" ] = local_var > p h > # do more stuff > } > } > end > > This defines a method "long_generated_method" for the given klass, using > two objects passed as parameters inside the method. You can call it like > > add_long_method_to_class String, [ 1, 2, 3 ], { "x" => 1 } > > "hi".long_generated_method > > This prints > > {"x"=>1, "s"=>3} Yes, your right, I had "blinders on" and really was missing your point. define_method opens up the scope. It's really kind of funny that it does so --or should I say that def does not. The fact that def's not a real method, like define_method makes all the difference. Then you're ecapsulating the whole thing using parameteres with which you can gernerate new varaitions on the method. That really can be amazingly powerful. Hm...I admit, I'm impressed. I'm going to keep this in the back of my mind for a while churning over application. There's something about, something compelling. My immediate impression is sort-of, "why do I use def at all?" I'm sure I'm over simplifying but it is at least worth some thought. > > P.S. Did you see Austin's post on core? > > No, seems I missed it. Looking into the archive, he wants to have a > template > > ACCESSOR_METHODS = %Q{self.rss_?_list << "?"} > > and then substitute values for the placeholders. For the first > placeholder he has to use his string substitution method, but for the > second he could directly pass an object, for example: > > ACCESSOR_METHODS = %Q{self.rss__list << value} > > He then can evaluate it like so: > > value = [ 1, 2, 3 ] # could be every object > module_eval ACCESSOR_METHODS.gsub( //, "element" ) > > Notice that the "value" in the ACCESSOR_METHODS template is substituted > by the "value" variable in the surrounding scope of module_eval. I can > remember that I have been very surprised when I first saw this magic in > someone's code (don't know where it was though). It is a really powerful > mechanism. Now this *is* a trip! I was just talking about this in an earlier discussion. Its dyanmic scoping. [ Actually I think I may have slightly misinterpreted Austin's post, but now to my benefit :-) ] I don't know if you caught that talk. Of course the problem with dynamic scoping is the dependency on specific varable names like 'value'. But in particular contexts you can reuse code, even pass it around. In generic contexts its even more useful. Take it to the extreme and you have almost total code reflection. Very interesting stuff!! > HTH IDID !!! -t0