Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 134 ยท Control Flow

Loops

Learn Ruby loops - while, until, loop, for and why it is rarely used, break with a value, next, redo, loop modifiers, begin/end while, and infinite loops.

A loop repeats a piece of code. Ruby has the loops you know from other languages, while and until, plus a simple loop method and a for keyword that experienced Rubyists avoid. Most day-to-day repetition in Ruby is done with iterators like each and times, which you will meet in Iterators and Blocks Basics. Still, while, until and loop are the right tools when you do not know in advance how many repetitions you need: reading until input ends, retrying until success, running a game loop, or waiting for a condition.

In this lesson you will learn each loop form, how break, next and redo steer them, how loops return values, and the common bugs, including endless loops.

while and until

while condition repeats the body as long as the condition is truthy. until condition is the mirror image: it repeats until the condition becomes truthy. Remember that in Ruby only nil and false are falsy (see if, elsif, else and unless).

Ruby while and until

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Both loops check the condition before each pass, so the body may run zero times. Use until when the positive wording reads better: until queue.empty? is clearer than while !queue.empty?.

Modifier form

A single statement can carry the loop after it, just like if.

Ruby Loop modifiers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The modifier form is fine for short, obvious statements. Do not stretch it over complicated expressions.

begin ... end while (run at least once)

Normally a while modifier checks first. If the statement is a begin ... end block, Ruby runs the block first and checks afterwards, like do ... while in C or Java.

Ruby Run the body at least once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first loop never runs, so x stays 100. The second runs once, giving 101. This trick works but surprises readers, and some style guides prefer the loop form shown next.

loop: the simple infinite loop

loop is not a keyword but a method that takes a block and repeats it forever, until you leave with break (or an exception ends it). It is the clean way to write "repeat until something happens in the middle".

Ruby loop with break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

One more useful property: loop rescues StopIteration and ends quietly. That makes it perfect for walking an external enumerator, covered in Enumerators and Lazy Enumerators.

Ruby loop stops on StopIteration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

break, next and redo

Three keywords steer a loop from the inside.

  • break leaves the loop immediately.
  • next skips the rest of this pass and moves on to the next one.
  • redo repeats the current pass without rechecking the condition. It is rare and easy to misuse.
Ruby break and next

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Both break and next can carry a value: break 42 makes the loop expression evaluate to 42, and in block form next 42 makes that pass of the block return 42.

A loop is an expression

while and until loops evaluate to nil unless you leave with break value. The loop method returns whatever break gave it. That makes search loops compact.

Ruby Returning a value with break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last line shows that a loop which ends normally returns nil. For searching a collection you should usually prefer find or index from Iterating and Transforming Arrays, but this form is handy when the search is not over a collection.

Nested loops and breaking out of both

break leaves only the innermost loop. To leave several levels, use a flag, move the loops into a method and return, or use catch/throw (see catch and throw).

Ruby Escaping two levels with a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Extracting the loops into a small method is usually the most readable choice.

Ruby has for item in collection. It works, but it is unusual in real code, because it is built on each with one important difference: it does not create a new scope.

Ruby for leaks its variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

After the for, the variable n is still alive, and the loop body can silently overwrite variables that are in use elsewhere. A block-based each keeps the variable inside the block. For that reason the community style is to use each, times and friends, and keep for for the rare quick script.

Common loop patterns

Counting loops

Ruby Counting with while versus times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

When you know the count, the iterator forms are shorter and cannot suffer from an off-by-one error from forgetting i += 1.

Reading until the input ends

gets returns nil at end of input, which is a natural loop condition. Any program that reads input must give the TryIt something to read.

Ruby Read lines until nil

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The parentheses around the assignment are a Ruby habit that says "yes, I really meant = here".

Retrying with a limit

Ruby Retry loop with a maximum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Always give a retry loop a cap. Real programs must never wait forever for a failing service.

Pitfalls

Forgetting to change the condition

If nothing in the body can change the condition, the loop never ends. In a terminal you press Ctrl+C. In our online runner, a time limit stops the program, so keep infinite loops out of examples unless they break.

Ruby
# read-only example: do not run
i = 0
while i < 5
  puts i      # missing i += 1, so this prints 0 forever
end

Modifying a collection while iterating

Adding or removing elements of an array while you loop over it with each leads to skipped or repeated items. Loop over a copy (list.dup.each) or build a new array with select and reject.

Assignment instead of comparison

Writing while x = 5 assigns instead of comparing, so the condition is always truthy. Ruby warns about it in some cases. Use == to compare.

Counting off by one

while i <= 3 runs for 1, 2 and 3. while i < 3 stops at 2. When iterating over ranges, the exclusive form 0...n ends before n; see Ranges.

Which loop should I use?

  • Know the collection? Use each, map, select: Iterators and Blocks Basics.
  • Know the count? Use n.times or upto.
  • Repeat while a condition holds? Use while or until.
  • Repeat until something in the middle happens? Use loop do ... break ... end.
  • Almost never for.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does n *= 2 while n < 100 do when n starts at 500?

    A plain while modifier checks the condition before running. Only begin ... end while runs the body first.
  2. 2. What value does while return when it finishes without break?

    A while or until loop evaluates to nil unless you leave it with break value.
  3. 3. What is different about for n in 1..3 compared with (1..3).each do |n|?

    for does not create a new scope, so n is still defined after the loop. A block parameter exists only inside the block.
  4. 4. What does next do inside a loop?

    next ends the current pass. break leaves the loop altogether.
  5. 5. Which loop is best when you want to repeat until something happens in the middle of the body?

    loop repeats forever until you break, so it fits cases where the exit condition is not at the start or the end.

Summary

  • while repeats while a condition is truthy, until repeats until it becomes truthy. Both check first.
  • begin ... end while cond runs the body at least once.
  • loop do ... end repeats forever until break, and quietly ends on StopIteration.
  • break leaves the innermost loop (optionally with a value), next skips to the next pass, redo repeats the current pass.
  • Loops are expressions: they return nil, or the value given to break.
  • for leaks its variable and is rarely used. Prefer each and times.
  • Always make sure the condition can change, and cap retry loops.

Next: Iterators and Blocks Basics