for循环中的Ruby局部变量

时间:2017-11-22 11:23:06

标签: ruby for-loop local-variables

我想知道是否可以在Ruby for循环中设置局部变量。

更确切地说,我想让for循环表现得像这样:

tmp = 0
1.upto(5) { |i;tmp| puts i; tmp = i; } ; "tmp: #{tmp}"

tmp变量不应该被foor循环内部运行的东西修改。

2 个答案:

答案 0 :(得分:1)

您可以引入一个新块来屏蔽外部变量

tmp = 0
for i in (1..5) do
  proc do |;tmp|
    puts i
    tmp = i
  end[]
end

这太糟糕了。 foreach之间的区别在于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循环没有自己的范围。