[Ruby] [Ruby] Behavior of conditional expression evaluation in while

1 minute read

Introduction

Note that I encountered the first behavior while using while.

Environment

ruby: 2.7.1

Phenomenon

Phenomenon _A

a = 0

while
  if a == 5
    break
  end
  a += 1
end

puts a
# Execution result: 0

Phenomenon_B

b = 0

while
  b += 1
  if b == 5
    break
  end
end

puts b
# Result: 5

Phenomenon_C

c = 0

while c <5 do
  c += 1
end

puts c
# Result: 5

Phenomenon_D

d = 0

loop do
  if d == 5
    break
  end
  d += 1
end

puts d
# Result: 5

Phenomenon_E

e = 0

loop do
  e += 1
  if e == 5
    break
  end
end

puts e
# Result: 5

▽ As an expected result, I thought that 5 would be output even in phenomenon_A.

Why this happens

(I was able to solve it by the comment of @scivola.)

Apparently, the expression immediately after while is evaluated as a conditional expression. In other words, in this phenomenon _A,

if a == 5
  break
end

This part is evaluated as the conditional expression of while for the first time, and of course a == 5 becomes false and the value of the if expression becomes nil, so it seems that the loop has been exited.

By the way, in Ruby all values except nil and false are true.

When the conditional expression is given as a test, the processing in the loop is executed.

a = 0

while true do # do is optional
  if a == 5
    break
  end
  a += 1
end

puts a
# Result: 5

The pitfall this time was that the expression inside the loop was actually a conditional expression.

Edit history

2020/07/04 17:11 I commented on the cause of the problem from @scivola in the comment, so I edited “Why this happens”. 2020/07/04 17:31 Changed the title to something more relevant and revised the text a little.

Remark

Normally, I don’t use while or loop, but use another method for iteration.

Tags:

Updated: