Why does this work:
a = [1, 2, 3]
while n = a.shift
puts n
end
while this doesn't:
a = [1, 2, 3]
puts n while n = a.shift
It works only if I initialize n in advance:
a = [1, 2, 3]
n = nil
puts n while n = a.shift
That is, in general, an interpreter problem, that could not appear in languages with local variable bubbling, like javascript.
The interpreter (reading from left to right) meets right-hand-operand n before any mention of it.
The more I think about it, the more I am convinced it is a bug in ruby interpreter. As @Cary pointed out, the control flow is in fact the same:
a = [2, 3]
n = 1
puts n while n = a.shift
#⇒ 2
#⇒ 3
No trail of 1 in the output above.
n is undefined at the time you attempt the first puts. The condition, and corresponding shift, is only checked after the puts has been evaluated. An alternative which will work as you expected would be
a = [1, 2, 3]
puts a.shift while a.length > 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With