From: "David A. Black" Date: 2007-08-18T20:29:12+09:00 Subject: Re: method access to the enclosing method's locals? Hi -- On Sat, 18 Aug 2007, david karapetyan wrote: > Ok, just ignore all my previous posts. I should have done some more research > before I started typing. This code will actually work. > > def go2(arg) > (class << self; self; end).class_eval do > define_method(:hi) do puts "Hi #{arg}" end > end > end > > Once you call go2 with some argument it will create the method hi that will > have access to any argument passed to go2. I have to say though all the > redirection with the singleton class makes my head spin a little. This isn't quite the same as doing an inner def, because you're defining #hi as a singleton method. If you want to define it as an instance method of the enclosing class, you would want to do: self.class.class_eval do ... As for the head spinning, hopefully someday we'll have this method in the core (and meanwhile you can write it yourself): class Object def singleton_class class << self; self; end end end Then you can do: singleton_class.class_eval do ... which is a little less cluttered. Also, keep in mind that it's not really redirection; it's just sending messages to objects :-) The fact that you can send messages to Class objects means that you can do what feels like "meta" stuff in much the same way that you do other things. David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)