From: Eric Mahurin Date: 2005-09-28T22:33:43+09:00 Subject: Re: creating independent lambdas in loops --- ts wrote: > >>>>> "M" == Michael Roth writes: > > M> a = [] > > M> for multi in [2, 3, 4, 5] > M> a << lambda do |n| > M> n * multi > M> end > M> end > > [2, 3, 4, 5].each do |multi| > a << lambda do |n| > n * multi > end > end The each loop works because the variable multi is local to the each block. Each iteration through that block will use a different variable multi. To me, it seems like a bug that the for loop isn't equivalent to the each loop. I think it is putting multi in the surrounding scope because of the syntactic order - multi comes before the Enumerable. You'll see the same problem if you assign multi before the each loop. If you wanted to continue using the for loop (or multi was already used), you could make a localized version of it like this: a = [] for multi in [2, 3, 4, 5] lambda do |multi_local| a << lambda do |n| n * multi_local end end.call(multi) end for mul in a puts mul.call(17) end I didn't realize that within a block, the only variables truly local are the argument variables. I think I've read somewhere that in the future ruby will put better facilities in for controlling variable scope locality. > M> for mul in a > M> puts mul.call(17) > M> end __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com