对于循环变量范围

问题描述:

使用此示例:对于循环变量范围

arr = [1, 2, 3] 

for elem in arr do 
    puts elem 
end 

puts elem # => 3 

代码输出:

1 
2 
3 
3 

elem包含连外循环的值。为什么?循环之外的范围是什么?

请问谁能澄清?

+0

自从循环引入范围时? – hek2mgl

+0

变量'elem'是否有范围? –

+1

'for'在Ruby代码中不推荐使用,因为它泄露了中间变量。相反,我们使用'each'或'upto'或'count'来迭代。 –

这是预期的。按照documentation

for循环类似于使用each,但不创建一个新的变量范围。

实例与 for

for i in 1..3 
end 
i #=> 3 

例与each

(1..3).each do |i| 
end 
i #=> NameError: undefined local variable or method `i' 

如果我没有记错,方法eachmaploopupto)创建变量的作用域,而关键字for,while,until)不。

你可以在循环范围外声明你的变量elem。因此,如果我们修改您的示例:

arr = [1, 2, 3]; 
elem; 

for elem in arr do 
    puts elem 
end 

puts elem # => 3 

for语句定义变量elem并使用当前循环的值对其进行初始化。

要避免这一点Array#each

arr.each do |elem| 
    puts elem 
end 
# 1 
# 2 
# 3 
# => [1, 2, 3] 
elem 
NameError: undefined local variable or method `elem' for main:Object 
    from (irb):5 
    from /usr/bin/irb:12:in `<main>' 

现在ELEM变量仅在块存在。