I wonder how the following closure test can be written in other languages, such as C/C++ and Java. Can the same result be expected also in Perl, Python, and PHP?
Ideally, we don't need to make a new local variable such as x
and assign it the value of i
inside the loop, but just so that i
has a new copy in the new scope each time. (if possible). (some discussion is in this question.)
The following is in Ruby, the "1.8.6" on the first line of result is the Ruby version which can be ignored.
p RUBY_VERSION
$foo = []
(1..5).each do |i|
$foo[i] = lambda { p i }
end
(1..5).each do |j|
$foo[j].call()
end
the print out is:
[MacBook01:~] $ ruby scope.rb
"1.8.6"
1
2
3
4
5
[MacBook01:~] $
Contrast that with another test, with i
defined outside:
p RUBY_VERSION
$foo = []
i = 0
(1..5).each do |i|
$foo[i] = lambda { p i }
end
(1..5).each do |j|
$foo[j].call()
end
the print out:
[MacBook01:~] $ ruby scope2.rb
"1.8.6"
5
5
5
5
5
[MacBook01:~] $