From: Michael Neumann Date: 2003-11-17T07:58:02+09:00 Subject: Re: Local Variable Scope in Ruby2 On Mon, Nov 17, 2003 at 07:21:15AM +0900, Harry Ohlsen wrote: > Michael Neumann wrote: > >Simple rule (Ruby 2.0): Block parameters are local to the block, > >everything else is not. > > > >Consider the following example (Ruby 1.8): > > > > a = 3 > > [1,2].each do |a| > > p a > > end > > p a # => 2 > > > >This problem is fixed with 2.0 (a => 3). > > So, with the new semantics, how do we do things like ... > > a = nil > > some_collection.each do |x| > if some_condition > a = ... > break > end > end This will work exactly the same way as in Ruby 1.8. The assignment inside the block will assign to the outer variable (a). Any assignment inside a block with the exception of assignements to block parameter variables (here x), will be to variables outside the block. > Obviously, if we want "a" to end up being the same as one of the values in > the collection, there's probably some iterator other than "each" that will > allow for that. However, if the value we want to give it is more complex > (or just plain different from the current value of x), what's the right > mechanism? > > Sorry, I can't think of a concrete example this second, but I can remember > doing this kind of thing many times in the past ... mainly because it > always failed until I added the "a = nil" line :-). In Rite you won't need a "a = nil" line anymore. "a=" inside the block will automatically introduce a variable "a" outside the block. Hopefully, I don't tell you something wrong :-) Regards, Michael