From: "David A. Black" Date: 2008-09-30T18:41:22+09:00 Subject: Re: ruby1.9 block scope Hi -- On Tue, 30 Sep 2008, Yukihiro Matsumoto wrote: > Hi, > > In message "Re: ruby1.9 block scope" > on Tue, 30 Sep 2008 09:10:39 +0900, Daniel DeLorme writes: > > |That was also my guess; it least it's an easy concept to imagine. But it > |does bring the question of what to do when you *don't* want variables to > |"escape" into the enclosing scope? e.g. > | > |class Foo > | defined_method :bar do > | x = 1 #I don't want x to be defined in the Foo scope > | end > | defined_method :baz do > | x = 2 #because it would wind up shared with this method > | end > |end > > As Nobu stated, you can explicitly declare block local variables, > using ';'. Besides that above code would not share variable x, since > the variable is not used upper level. They are two distinct > variables at the same level, with a same name. See the following > code, that makes a variables shared among blocks: > > class Foo > defined_method :bar do > x = 1 > end > defined_method :baz do > x = 2 > end > x = 45 # this assignment would make x shared with foo and bar under the new rule. > end > > The reason I haven't introduced it yet in Ruby is that single > assignment after the blocks can change the scope of a variable > afterward. Same thing happens assignments _before_ the blocks > already. But I hesitated to enhance that far. Please continue to hesitate :-) That would be very hard to deal with. As a reader of the code, you'd have to do a two-pass visual scan before you could begin to understand any of it. And you would have to do that for *every* block, just in case, even if only 1% of them had a variable defined later. David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!