From: "Jesús Gabriel y Galán" Date: 2010-05-05T18:04:14+09:00 Subject: Re: for-in vs. map closures On Wed, May 5, 2010 at 8:35 AM, Mike Austin wrote: > I was experimenting with closures and JavaScript's and Ruby's > behavior.  Ruby seems to close over its arguments automatically if > using map: > > [1, 2, 3].map { |n| lambda { n * n } }.map { |b| b.call() }  # [1, 4, > 9] Here, n is local to the block, so the n in the lambda is different every time. The lambda is a closure over the scope of the block, and in that block the variable n is different in each iteration. > But using "for" iteration, returns a different result: > > a = [] > for n in [1, 2, 3] do a << lambda { n * n } end > a.map { |b| b.call() }  # [9, 9, 9] Here n is the same in all iterations (it's outside the do ... end), for defines it in the scope that is above the block, so it's the same for all iterations. The lambda closes over that scope, but the n in all lambdas point to the same object. So after the loop, n is 3, and so all lambdas see 3 as the value. Jesus.