Thuta Learning
Ruby
IntermediateProgrammingBeginner

Loops (While, Until)

RubyLesson 1330 min

What you'll walk away with

  • Write while and until loops and move the condition so the loop cannot run forever
  • Tell break (with a value), next and redo apart, and know why break only leaves the innermost loop
  • Use times, upto, downto, step and ranges for loops whose pass count is known
  • Explain how a for loop leaks its variable and decide when each is the better choice

Explain it simply

Explain it simply

A loop tells Ruby to keep doing something until a condition says stop. Think of stirring a pot of soup: you repeat one action, and after every stir you look at the pot to decide whether to keep going. while keeps stirring as long as a condition is true, and until keeps stirring until a condition becomes true.

Ruby offers several ways to say this. while and until check a condition before every pass, loop do ... end repeats until you break out of it, and helpers such as 3.times repeat a fixed number of times. To walk through a collection, Rubyists usually prefer each over a manual counter, which the next lesson covers.

Problem → Why → Solution

The problem: a loop that never stops

When you poll a download until it finishes, or read numbers until the user types quit, you cannot know in advance how many passes it will take. A fixed list of steps will not do; you need a loop. The loop below tries to count down from 3, but its author forgot one line. Run it and the terminal prints the same number forever until you press Ctrl+C.

countdown_bug.rb
countdown = 3

while countdown > 0
  puts "T-minus #{countdown}"
  # forgot: countdown -= 1
end

puts "Liftoff!"   # never reached

Why does the loop never stop?

A while loop only re-checks its condition; it never changes anything by itself. Nothing in the body touches countdown, so countdown > 0 is true on every check and Ruby has no reason to stop. The fix is always the same: something inside the loop must push the condition toward false, by updating the variable, reading the next input or calling break.

Core concept: condition, body and exit

A while loop has three working parts: a condition, a body, and something inside the body that eventually makes the condition false. Ruby evaluates the condition first, runs the body if the result is truthy, and then jumps back to evaluate the condition again. until is the mirror image: it runs the body while the condition is falsy, so until x == 3 behaves like while x != 3. Pick whichever reads more naturally; until usually reads better for waiting loops such as until finished.

Truthiness matters here. In Ruby only nil and false are falsy; every other value, including 0, the empty string and the empty array, counts as true. So a loop written as while count, with count equal to 0, never stops, because 0 is truthy. Write the comparison you actually mean, such as while count > 0. Both while and until are expressions that return nil, unless you leave early with break and a value.

When there is no natural condition, use loop do ... end. It repeats until something inside it leaves. break exits the loop immediately and can carry a value (break 42), while next skips the rest of the current pass and begins the next one. loop also ends quietly when the code inside raises StopIteration, which is how it cooperates with the external enumerators you will meet in the Enumerable lesson. A third keyword, redo, restarts the current pass without re-checking anything. It is rarely a good idea, so know that it exists but do not reach for it.

Ruby also has for item in collection, but experienced Rubyists almost never write it. The reason is scope: a for loop does not create a new scope for its variable, so the variable is still alive after the loop finishes, whereas the block variable of each disappears when the block ends. That leak invites accidental name clashes. As a rule of thumb, use while and until when the number of passes depends on a condition that changes, and use each, times, upto and step when you are walking a known collection or range.

Mental model: check, run, change, repeat
  1. Check the condition (truthy or not?)
  2. Run the body once
  3. Change something the condition reads
  4. Jump back to the check

break and next are exits you add yourself: break leaves the loop, while next jumps straight to the next check.

General pattern

ruby
while condition
  body
end

until condition
  body
end

loop do
  break if done
  next if skip
end

while repeats the body as long as the condition holds, and until repeats it until the condition becomes true. loop do ... end has no condition, so you write the exit yourself with break, and next skips the rest of one pass. The closing end is never optional.

Example: one while, one until and one loop

This example uses all three styles. The while loop counts from 1 to 3, the until loop keeps going until the attempt counter reaches 3, and the final loop do skips odd numbers with next and stops itself with break.

Notice that every variable is created before its loop. count, tries and n are set up first and then changed inside the body, which is what lets the condition eventually flip.

loops.rb
count = 1
while count <= 3
  puts "while: #{count}"
  count += 1
end

tries = 0
until tries == 3
  tries += 1
  puts "until: attempt #{tries}"
end

n = 0
loop do
  n += 1
  next if n.odd?
  puts "loop: #{n}"
  break if n >= 6
end

Code breakdown

  1. whilewhile count <= 3

    Checked before every pass. When count becomes 4 the condition is false and Ruby jumps to the line after end.

  2. updatecount += 1

    The line that pushes the condition toward false. Delete it and count stays at 1 forever, exactly like the loop in the problem section.

  3. untiluntil tries == 3

    until runs while the condition is false, so it reads like waiting for tries to reach 3. tries += 1 comes first, which is why the printed attempt numbers are 1, 2 and 3.

  4. nextnext if n.odd?

    When n is odd (1, 3, 5) the rest of this pass is skipped and the loop goes back to the top, so only the even numbers get printed.

  5. breakbreak if n >= 6

    loop do has no condition, so this line is its only exit. It runs after 6 has been printed, which is why 6 appears in the output.

You should see
while: 1
while: 2
while: 3
until: attempt 1
until: attempt 2
until: attempt 3
loop: 2
loop: 4
loop: 6
How one while loop runs
  1. Evaluate the condition
  2. If it is truthy, run the body
  3. The body changes some state
  4. Go back to the condition

Condition is falsy

Skip to the line after end and carry on with the program

The body changes nothing

Infinite loop: stop it with Ctrl+C

Counting loops: times, upto, step and ranges

When you know how many passes you need, you do not have to manage a counter variable yourself. n.times counts from 0 to n - 1, while a.upto(b) and b.downto(a) count up or down between two numbers. step lets you choose the jump size, including negative jumps and floats. Called without a block, these methods return an Enumerator, so adding .to_a shows all the values at once.

counting.rb
3.times { |i| puts "time #{i}" }   # i counts 0, 1, 2

p 1.upto(4).to_a                   # [1, 2, 3, 4]
p 4.downto(1).to_a                 # [4, 3, 2, 1]
p 1.step(10, 4).to_a               # [1, 5, 9]
p 10.step(1, -3).to_a              # [10, 7, 4, 1]
p 1.0.step(2.0, 0.5).to_a          # [1.0, 1.5, 2.0]
p((1..10).step(3).to_a)            # [1, 4, 7, 10]
p(("a".."e").to_a)                 # ["a", "b", "c", "d", "e"]
p((1...4).to_a)                    # [1, 2, 3]  (three dots exclude the end)

A range with two dots, (1..10), includes its last value, while three dots, (1...10), excludes it. That difference is behind many off-by-one bugs, so keep it in mind. Because a range can be walked directly with each, step or to_a, you rarely need a while loop with an index at all.

break, next, redo and nested loops

KeywordWhat it doesValue it returns
breakLeaves the loop at onceThe value you pass (nil if none)
nextEnds this pass and starts the next oneThe value for this pass (nil if none)
redoRestarts this pass without any checkNone, the pass simply begins again

Using break with a value turns the loop into an expression you can assign. If nothing breaks, each simply returns the original array. The second point is nested loops: break leaves only the innermost loop, and the outer loop carries on with its next pass. To leave both loops at once you can use catch and throw, or put the loops inside a method and return from it.

break_next.rb
first_big = [3, 8, 12, 5].each do |n|
  break n if n > 10
end
p first_big                  # 12

evens = []
(1..6).each do |n|
  next if n.odd?
  evens << n
end
p evens                      # [2, 4, 6]

(1..3).each do |a|           # break only leaves the inner loop
  (1..3).each do |b|
    break if b == 2
    puts "a=#{a} b=#{b}"
  end
end

pair = catch(:found) do      # throw leaves both loops
  (1..3).each do |a|
    (1..3).each { |b| throw :found, [a, b] if a * b == 6 }
  end
  nil
end
p pair                       # [2, 3]

In the first loop, break fires as soon as 12 appears and 12 lands in first_big. In the second, next skips the odd numbers so evens holds only 2, 4 and 6. The nested loop prints three lines, a=1 b=1, a=2 b=1 and a=3 b=1, because break ends each inner loop before b reaches 2 while a still runs up to 3. Finally catch and throw jump out of both loops the moment a pair with 2 * 3 == 6 is found.

Two quirks: the for leak and begin...end while

After a for loop its variable is still alive, while the block variable of each is gone. Try it in the code below. The other quirk is the modifier form (puts n while n < 3) versus begin ... end while condition. The modifier checks the condition first and may never run the body, but the begin ... end form runs the body at least once before checking. That is how Ruby writes a do-while loop.

quirks.rb
for i in 1..3
  # body
end
puts "after for: i = #{i}"      # the loop variable leaked

[10, 20, 30].each { |x| x }
p defined?(x)                   # nil: each's block variable is gone

m = 5
puts "modifier: #{m}" while m < 3
puts "m is still #{m}"          # the body never ran

n = 5
begin
  puts "begin/end: #{n}"        # runs once even though 5 < 3 is false
  n += 1
end while n < 3

In real projects

Where this shows up in real projects

Real programs use while, until and loop wherever the number of passes is not known in advance. A script that polls a job until it is done, a retry that waits and tries again up to five times, a command-line menu that runs until the user types quit, and a game's main loop that updates and draws until the player exits are all driven by a condition. A typical polling loop reads until job.finished? || attempts == 5 with a sleep inside, and notice that it has two ways to stop, because a loop that can only end on success is a loop that can hang a server.

Loops over collections look different in everyday code. Most Ruby you read uses each, map, times and friends, which cannot run forever because the collection or range supplies the end. Servers and workers do use loop do ... end on purpose for their main cycle, usually with a break or a signal handler for shutdown. When you review code, look at every while or loop and ask what changes inside it and what the maximum number of passes is.

Common mistakes

Common mistakes

1. Forgetting to move the condition

A while loop whose body never changes anything the condition reads runs forever. The countdown in the problem section is the classic case, but it also happens with an until that waits for a flag nobody sets. Make it a habit to point at the line inside the body that moves the loop toward its end. When a terminal hangs, press Ctrl+C and Ruby stops with an Interrupt.

2. Treating 0 or a string as false

People who come from languages where 0 or an empty string is false write while remaining or puts 'yes' if '' and are surprised. In Ruby both are truthy, so while remaining with remaining equal to 0 loops forever and puts 'yes' if '' prints yes. Compare explicitly with remaining > 0 or name.empty?.

3. An off-by-one at the end of an index loop

A loop such as while i <= names.length reads one position past the end. On a three-element array names[3] is nil, and calling upcase on it raises NoMethodError: undefined method 'upcase' for nil (this is the message format Ruby 4.0.9 prints). Use i < names.length, or better still names.each.

4. Expecting break to leave every loop

break exits only the innermost loop or block. With two nested loops it leaves the inner one and the outer loop carries on with its next pass. To leave both, put the loops in a method and return from it, or wrap them in catch and throw.

Best practices

Best practices

  • Give every while or until loop that depends on something outside your program a second exit, such as a maximum number of attempts.
  • Choose each, map and times when you walk a collection or know the pass count, and keep while and until for conditions that change.
  • Write the comparison out, as in while count > 0, instead of relying on the truthiness of a number.
  • When nested loops and break creep in, move them into a method that returns the answer.

Mini challenge

Mini challenge: a Collatz chain explorer

The Collatz process starts with any positive integer: if it is even, halve it; if it is odd, triple it and add 1. Repeat until you reach 1. Write two helpers that explore it and print a small report.

  • collatz_steps(start) counts the steps until the value reaches 1, using an until loop, and returns the count
  • first_longer_than(limit) uses loop do with break to return the smallest start whose chain takes more than limit steps
  • Print the step count for 5, 6, 7 and 27 using each
  • Print the first start that needs more than 20 steps
collatz.rb
def collatz_steps(start)
  # TODO: keep a running value and a step counter,
  #       loop with until and return the number of steps
end

def first_longer_than(limit)
  # TODO: try start = 1, 2, 3, ... inside loop do
  #       and break as soon as a chain is longer than limit
end

# TODO: print lines like "5 -> 5 steps" for 5, 6, 7 and 27
# TODO: print "first start over 20 steps: ..." using first_longer_than(20)

Expected: 5 -> 5 steps 6 -> 8 steps 7 -> 16 steps 27 -> 111 steps first start over 20 steps: 25

Show hint

Use n.even? to test the parity, then n = n.even? ? n / 2 : 3 * n + 1 does the update. In first_longer_than start with candidate = 1, write break candidate if ... inside the loop, and add 1 to candidate when the check does not fire.

Show solution
collatz.rb
def collatz_steps(start)
  n = start
  steps = 0
  until n == 1
    n = n.even? ? n / 2 : 3 * n + 1
    steps += 1
  end
  steps
end

def first_longer_than(limit)
  candidate = 1
  loop do
    break candidate if collatz_steps(candidate) > limit
    candidate += 1
  end
end

[5, 6, 7, 27].each do |start|
  puts "#{start} -> #{collatz_steps(start)} steps"
end

puts "first start over 20 steps: #{first_longer_than(20)}"

Quick quiz 1 / 3

After i = 10 and then i -= 3 while i > 0, what does puts i print?

Quick quiz 2 / 3

After for n in [4, 5, 6] ... end finishes, what does puts n do?

Quick quiz 3 / 3

With n = 5, how many lines does begin puts "n is #{n}"; n += 1 end while n < 3 print?

What to remember

  • while repeats as long as its condition is truthy and until repeats until it becomes truthy; something in the body must change the condition.
  • Only nil and false are falsy in Ruby, so 0 and the empty string are truthy: never use a bare number as a condition.
  • break leaves only the innermost loop (and can carry a value), next skips the rest of one pass, and redo is best avoided.
  • for leaks its variable, so walk collections with each, times, upto and step and keep while and until for changing conditions.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Loops (While, Until) | Thuta Learning