From: Yuh-Ruey Chen Date: 2008-11-01T03:49:01+09:00 Subject: Re: How to access to local variables in enclosing scopes? On Oct 31, 12:59 pm, Robert Dober wrote: > Ruby, in it's infinite wisdom; gives you a cake that you can have and eat. > > x =  42 > def a; x end # does not work!! > Why? > Because it is efficient, there is no closure and that means one > context less to look up at runtime. Not particularly convinced with that. If Python handles it with ease and apparently no runtime performance penalty, I don't see why Ruby can't do the same. I'm more convinced with the fragility argument I gave in my previous post, which is why I proposed the "nonlocal" thing. > If however you want the closure (as I often do) you can still do it > > x = 42 > > class << self; self end.module_eval do >   define_method :a do x end >   define_method :a= do |new_x| x = new_x end > end > > puts a > a = 43 > puts a > #! The next one is important ! > puts x > > Note the class << self; self end.module_eval > but I guess you know why I am doing this... > > .. class << self >  end > > does not create a closure. That's pretty clever, albeit somewhat unreadable. I'd prefer to keep Ruby as readable as possible :)