Jump to content

Closures/Value capture: Difference between revisions

(Added Racket)
Line 810:
 
=={{header|Ruby}}==
<lang ruby>irb(main):001:0> list = {}; (1..10).each {|i| list[i] = proc {i * i}}
(1..10).each {|i| list[i] = proc {i * i}}
=> 1..10
irb(main):002:0>p list[3].call #=> 9
p list[7][] #=> 49
=> 9
i = 5
irb(main):003:0> list[7][]
p list[3].call #=> 499</lang>
 
This works because ''i'' in <code>(1..10).each {|i| ...}</code> is local to its block. The loop calls the block 10 times, so there are 10 different variables to capture.
Line 822:
 
However, (on both Ruby 1.8 and 1.9) when using a for loop, the loop variable is shared and not local to each iteration:
<lang ruby>irb(main):001:0> list = {}; for i in 1..10; list[i] = proc {i * i}; end
for i in 1..10 do list[i] = proc {i * i} end
=> 1..10
irb(main):002:0>p list[3][] #=> 100
i = 5
=> 100</lang>
p list[3][] #=> 25</lang>
 
=={{header|Scheme}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.