简体   繁体   中英

Ruby local variables in a for loop

I would like to know if it is possible to set local variables in Ruby for loop.

More precisely I would like to have the for loop to behave like this:

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

The tmp variable should not be modified by what runs inside the foor loop.

You can introduce a new block for masking the outer variable

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

This is awful. The difference between for and each is that the iteration variable in a for loop pollutes the outer scope .

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]

Using my hack above to make your for act more like an each makes already confusing behavior even more confusing. Better to avoid for entirely.

我认为这是不可能的, for循环没有自己的作用域。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM