我想知道是否可以在Ruby for
循环中设置局部变量。
更确切地说,我想让for
循环表现得像这样:
tmp = 0
1.upto(5) { |i;tmp| puts i; tmp = i; } ; "tmp: #{tmp}"
tmp
变量不应该被foor循环内部运行的东西修改。
答案 0 :(得分:1)
您可以引入一个新块来屏蔽外部变量
tmp = 0
for i in (1..5) do
proc do |;tmp|
puts i
tmp = i
end[]
end
这太糟糕了。 for
和each
之间的区别在于for
循环中的迭代变量污染了外部范围。
x = []
# i has same scope as x
for i in (1..3)
# closure captures i outside the loop scope, so...
x << lambda { i }
end
# WAT
x.map(&:call) # [3, 3, 3]
x = []
(1..3).each { |i| x << lambda { i } }
# sanity restored
x.map(&:call) # [1, 2, 3]
使用上面的hack让你的for
行为更像each
,这使得已经令人困惑的行为更令人困惑。最好完全避免for
。
答案 1 :(得分:0)
我认为这不可能,for
循环没有自己的范围。