Why do I get an infinite loop in my ruby script?

Viewed 99

According to the description, the operator ||= will assign values ​​only once, but it looks like it does it every time and we have an infinite loop. (using Ruby 2.6.6p146)

loop do
  fib ||= [0,1]
  p fib
  i = fib[-1] + fib[-2]
  break if i >= 100
  fib << i
  p fib
end

# [0, 1]
# [0, 1, 1]
# [0, 1]
# [0, 1, 1]
# [0, 1]
# [0, 1, 1]
# ...
1 Answers

It's because your loop do ... end creates a new block scope.

The behavior is different if you have an outer variable fib:

fib = nil
loop do
  # ... your stuff here
end

In that case, calling fib ||= in the block would change the outer fib variable (because it's in the outer scope).

But since you have no outer variable fib, each time your loop block runs, fib is undefined again.

Related