Gok*_*l M 1 ruby scope for-loop
使用此示例:
arr = [1, 2, 3]
for elem in arr do
puts elem
end
puts elem # => 3
Run Code Online (Sandbox Code Playgroud)
代码输出:
1
2
3
3
Run Code Online (Sandbox Code Playgroud)
elem包含循环外的值.为什么?循环外的范围是什么?
有人可以澄清吗?
这是预料之中的.根据文件:
该
for循环类似于使用each,但不创建一个新的变量范围.
示例for:
for i in 1..3
end
i #=> 3
Run Code Online (Sandbox Code Playgroud)
示例each:
(1..3).each do |i|
end
i #=> NameError: undefined local variable or method `i'
Run Code Online (Sandbox Code Playgroud)
如果我没有记错的话,方法(each,map,loop,upto)创建变量的作用域,而关键字(for,while,until)没有.