Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby inline while vs while end

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
like image 242
Neves Avatar asked Sep 30 '15 03:09

Neves


2 Answers

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.

like image 51
Aleksei Matiushkin Avatar answered Oct 06 '22 00:10

Aleksei Matiushkin


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
like image 22
pjs Avatar answered Oct 06 '22 00:10

pjs