From: "David A. Black" Date: 2008-11-29T01:03:35+09:00 Subject: [ruby-core:20153] Re: [Bug #797] bug or feature: local method ? Hi -- On Sat, 29 Nov 2008, Francoys wrote: > Diogo Lisboa wrote: >> On Wed, Nov 26, 2008 at 4:32 PM, Francoys wrote: >> >>> declaring variables inside a method that are accessibles to all the >>> nested methods. >>> >> >> This isn't possible though. >> >> def foo >> bar = 10 >> def gazonk >> p bar >> end >> end >> >> >>>> gazonk # => undefined local variable or method `gazonk' >>>> foo # => nil >>>> gazonk # => undefined local variable or method `bar' >>>> >> >> >> This doesn't work because the chained method is in a whole new scope >> which doesn't know anything about the outer method's local variables. >> >> But, however odd this functionality is, I think it would be useful for >> the enclosing method to inherit the outer scope. You'd get something >> like named closures, and calling `gazonk' after `foo' would be able to >> print 10. >> >> However, this wouldn't be consistent, meaning, it should have to work >> if you declared a local variable in a class definition and all the >> methods would be aware of that; at this point, things get ugly. >> >> I think the idea of 'named closure' could be interesting (I don't know >> what consequences this would have, but sounds like a feature more than >> a bug). It beats returning lambdas in an array. >> >> Would you, enlightened ones, share your opinions on this? On the idea >> of the local methods being a bug or feature, I don't think they count >> much as a feature the way they currently are. >> >> >> Diogo >> >> >> > Try this one: > > def foo > @bar = 10 > def gazonk > print @bar > end > gazonk > end > > foo That's very different, though, because you're redefining your inner method every time *any* instance of the class calls the outer method, and you're using instance variables so there's no closure effect. class C def x @a = 1 def y p @a end end end c = C.new c.x c.y # 1 d = C.new d.y # nil David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS (Jan 12-15) | ADVANCING WITH RAILS (Jan 19-22) * Both in Fort Lauderdale, FL * Co-taught with Patrick Ewing See http://www.rubypal.com for details Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2)