From: Pit Capitain Date: 2003-11-30T08:34:20+09:00 Subject: Re: Controlled block variables Hi T. > Okay, I think I know what you're saying. So you're defining a method for > the variable that would be visible from within the def. Another viable > solution. > > I imagine we could even abstract this further using: > > class Object > def methodize(sym, var) > class_eval "define_method "#{sym}meth", proc{ var }" > end > end That's more or less what I did in my first post. But I think you still don't see the full potential. You can do much more in the proc than simply returning an object. In fact, when you wanted to write a = [1,2,3] class_eval %{ def meth end } 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} > 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. HTH Regards, Pit