Lesson 8 of 23 · Ruby 3.3
Repeat with a condition
Repeat work with while and until, and control repetition with break and next.
Learn
A while loop checks its condition before each repetition and runs its body while the condition is true. Update the value used by the condition so the loop can finish. An until loop instead repeats while its condition is false.
break leaves the loop immediately. next skips the rest of the current repetition and starts the next condition check. Keep any necessary counter update before next so that skipping work does not prevent the loop from ending. The form break if condition performs break only when that condition is true; next if condition works the same way.
Example
step = 1
while step <= 3
puts "Packing box #{step}"
step = step + 1
endExperiment
Predict how many additions happen. Change capacity to 6 and observe when until stops.
Predict which attempts are printed. Change target to 2 and trace whether the line after break runs on the matching attempt.
Predict the printed ticket numbers. Move the reserved number from 3 to 4 and check that the loop still finishes.