From: Mike Austin Date: 2010-05-05T15:35:07+09:00 Subject: for-in vs. map closures 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] 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] This is also the behavior in JavaScript, which frequently catches developers off guard when attaching event handlers to elements. Can anyone explain the difference? Is map creating a new anonymous function every iteration? Mike