From: pharrington Date: 2010-01-13T05:05:07+09:00 Subject: Re: instance_eval with local variable On Jan 12, 2:57 pm, Phrogz wrote: > On Jan 12, 12:23 pm, Phrogz wrote: > [snip]> For those interested in second-guessing my approach and coming up with > > a better way to achieve the same end goal > > FWIW, there is a workaround I've come up with. Instead of trying to > evaluate the proc in the scope and access instance variables directly, > I can pass the object to the proc and work from its public interface. > My original code is thus changed: > > > def self.process_snippets( html ) > >   @snippets.inject(html){ |h,(regexp,handler)| h.gsub( regexp, &handler ) } > > def self.process_snippets( html, bundle ) >   @snippets.inject(html){ |h,(r,proc)| h.gsub(r){ |s| proc > [s,bundle] } } > > >   # Mark $$foo$$ as glossary items. > >   DocuBot.handle_snippet /\$\$\w[^$]+\$\$/ do |match| > >     # TODO: look up the glossary term in the bundle's glossary > >     # and insert appropriate text, or flag a new glossary term > >     "#{match[2..-3]}" > >   end > > DocuBot.handle_snippet /\$\$\w[^$]+\$\$/ do |match, bundle| >   term = match[2..-3] >   defn = bundle.glossary[term] >   "#{term}" > end > > I'm thus unblocked in my endeavors, but still interested in the > metaprogramming needed to accomplish my original goal. I was actually > a little surprised that instance_eval doesn't take an arbitrary number > of arguments in the block form and splat them along to the block's > parameters. Well, I'm not sure if this is the particular sort of nastiness you're looking for, but.... defining a new method with the proc works.. xeno@amrita:~/projects $ cat nasty.rb obj = Object.new obj.instance_variable_set :@who, "foo" @who = "main" holla = lambda {|str| p @who, str} class << obj def eigen class << self; self; end end end obj.eigen.send(:define_method, :holla, &holla) obj.holla "horrah" xeno@amrita:~/projects $ ruby nasty.rb "foo" "horrah"