M
Mike Austin
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
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