Skip to the workspace
Pebellslearn by building
Loops and Iteration  ›  Lesson

while, until and loop

while 12 minwhile repeats as long as its condition is true and until as long as it is false, both checking before each pass, while loop with break is the clear way to run at least once.

ruby / while, until and loop

Explore each scene at your own pace.

01 · The rule

The rule

while, until and loop

while repeats as long as its condition is true and until as long as it is false, both checking before each pass, while loop with break is the clear way to run at least once.

Trace preconditions and stopping decisions for repeated work.

Bean Cart's espresso machine needs to heat up before the first order: keep checking the temperature until it reaches 93 degrees. You do not know in advance how many checks that takes. When a loop depends on a condition rather than a count, Ruby reaches for while, until and loop.

The rule

while runs as long as true; until runs as long as false.

A while loop checks its condition before each pass and stops the first time it is falsy:

temp = 20
while temp < 93
  temp += 25
  puts "Heating... #{temp}"
end
# Heating... 45, Heating... 70, Heating... 95

until is the mirror image, exactly as unless mirrors if. It keeps going while the condition is falsy and stops once it becomes true:

temp = 20
until temp >= 93
  temp += 25
end

Both have a one-line modifier form: temp += 25 while temp < 93.

Because the condition is checked first, the body may run zero times: with temp = 95, neither loop above runs at all.

Sometimes you need the body to run at least once, the classic "do/while". Ruby can write it by putting while after a begin ... end block:

begin
  reading = sensor_temperature
end while reading < 93

This form checks the condition after each pass. It works, but Ruby's creator has advised against it because it behaves differently from the modifier form, and style guides agree. The clearer Ruby idiom is loop with break:

loop do
  reading = sensor_temperature
  break if reading >= 93
end

loop do ... end repeats forever until something inside stops it, which makes the exit condition sit exactly where it is checked.

Whatever you choose, make sure the body changes something the condition depends on. If temp never changes, while temp < 93 never ends. Press Ctrl+C to stop a runaway loop in the terminal.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.