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
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.
Regarding: puts n while n = a.shift
,
it will pares puts n
first, but n
is undefined at that point. Ruby is a dynamically typed language; you don't declare variable type explicitly, but you should assign a value to variables.
For example:
irb(main):027:0> xyz
NameError: undefined local variable or method `xyz' for main:Object
irb(main):028:0> xyz = 1
=> 1
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