If I have:
2.times do
i ||= 1
print "#{i} "
i += 1
print "#{i} "
end
I get 1 2 1 2
, whereas I was expecting 1 2 2 3
. Why does i
lose its assignment when the loop starts over? It behaves as expected if the assignment occurs outside the loop, so I guess it has to do with scope, but I didn't realize loops have their own scopes. Can someone clarify?
Update: Thanks for the help on this. Part of my confusion stemmed from coming to Ruby from Python, which doesn't have block scope (I think).