Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 134 ยท Control Flow

Loop Control: redo, retry and next/break in Blocks

Master Ruby flow control inside blocks and loops - next and break values, redo, retry in rescue, StopIteration, LocalJumpError, and how to leave nested loops cleanly.

You already know while, until and each from Loops and Iterators and Blocks Basics. This lesson covers the corners: what exactly next and break do inside a block, what value they produce, the rarely used redo, the keyword retry that belongs to rescue, and how to get out of several loops at once. These corners cause real bugs (a break that leaves the wrong thing, a retry that loops forever), so it pays to know the rules precisely.

The key idea is that Ruby has four ways to leave or repeat part of a block or loop, and each one aims at something different.

flowchart TD
  K{"Keyword"} --> N["next<br/>leave THIS iteration<br/>(block returns a value)"]
  K --> B["break<br/>leave the method that<br/>yielded to the block"]
  K --> RD["redo<br/>run THIS iteration again<br/>(no new element)"]
  K --> RT["retry<br/>re-run the begin block<br/>from inside rescue"]

Each keyword targets a different point: the iteration, the whole iterator call, the same iteration again, or the protected block.

next: finish this iteration

In a loop, next jumps to the following iteration. In a block, it ends the block call and makes the block return a value, nil by default or the value you give it. That value matters for methods such as map and select, which use what the block returns.

Ruby next with and without a value

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.

next is the clean way to write guard clauses inside blocks: handle the unwanted cases at the top and keep the main work unindented. It cannot be used outside a block or loop; at the top level of a method body it is a syntax error. To leave a method, use return.

break: leave the iterator

break ends the method call that the block was attached to (not just the block) and makes that call return the value given to break, nil by default. Remember that each is just a method that yields to your block; break stops that method.

Ruby break returns a value from the iterator call

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.

This is why you can write found = list.each { ... break item ... }, but for searching, find, detect, any? and index are usually clearer (see Enumerable). Prefer them when they fit.

break, return and procs

break belongs to the method that received the block. That gives surprising results with procs and lambdas stored in variables (see Procs and Lambdas).

Ruby break and next with procs and lambdas

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.

In short: inside a block, break leaves the yielding method and return leaves the enclosing method; inside a lambda, both just leave the lambda. A bare proc whose home method has finished cannot break and raises LocalJumpError.

redo: run this iteration again

redo restarts the current iteration of a loop or block without checking the loop condition and without taking the next element. It is rarely needed and easy to misuse, which is why many Ruby programmers have never written it. A legitimate case is "try this item again after fixing something", with a counter so it cannot spin forever.

Ruby redo with a safety counter

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.

Careful with that first example: redo re-runs the block with the same block arguments, so the changed item is a local variable reassignment inside the block. The passes hash counts by the original text, and because the repaired name differs, it is not counted twice. The guard passes[item] == 1 is what prevents an endless loop.

An unconditional redo, or one whose guard never becomes false, is an infinite loop. In most cases a small inner while loop or a separate method that retries a single item is clearer. Ruby 3.x and 4.0 still support redo, but you will see it in very little real code.

retry: run the begin block again

retry is not a loop keyword at all; it is part of exception handling. It may appear only inside a rescue clause and restarts the begin ... end block (or the method body) from the top. It is the natural way to say "try again if that fails".

stateDiagram-v2
  [*] --> Trying
  Trying --> Done: success
  Trying --> Failed: exception raised
  Failed --> Trying: retry (attempts left)
  Failed --> GaveUp: re-raise (no attempts left)
  Done --> [*]
  GaveUp --> [*]

retry sends control back to the start of the protected code; always bound the number of attempts.

Ruby retry with a bounded number of attempts

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.

retry also works in a rescue clause of a whole method body. Local variables keep their values across the retry, which is why the examples count attempts in a local variable that is set before the begin. If you put the counter inside the begin, it resets on every retry and the loop never ends.

In real code add a wait between attempts, usually exponential backoff (sleep 2**attempts plus a little random jitter), and retry only errors that are really transient (timeouts, connection resets), never programming errors such as NoMethodError. See Exceptions and Custom Exceptions for designing the errors you want to retry.

StopIteration and external iteration

The loop method has a special feature: it rescues StopIteration and ends quietly, returning the exception's result. That is how a loop over an enumerator's next stops by itself.

Ruby loop ends 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.

External iteration with next is described in Enumerators. Notice that Enumerator#next (a method) and the keyword next (loop control) are different things that share a name.

Leaving nested loops

break leaves only the innermost iterator. To jump out of several levels you have three options:

  1. Put the loops in a method and return. This is usually the cleanest.
  2. Use catch/throw to unwind any number of levels (see catch and throw).
  3. Keep a flag that the outer loop checks. Simple, but easy to forget to reset.
Ruby Three ways out of nested loops

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.

Quick reference

You write It means Result value
next / next v End this block call or loop pass The block returns nil / v
break / break v End the iterator method call The call returns nil / v
redo Restart this iteration none
retry Re-run the begin block (only in rescue) none
return v Leave the enclosing method (a lambda leaves itself) The method returns v
throw :tag, v Unwind to catch(:tag) catch returns v

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [1, 2, 3].map { |n| next if n == 2; n * 10 } return?

    next without a value makes the block return nil for that element, and map keeps the nil in place.
  2. 2. What does break 5 inside list.each { ... } do?

    break ends the method that the block was given to, and that call evaluates to the value of break.
  3. 3. Where can retry be used?

    retry restarts the begin block (or method body) and is only valid inside rescue. Always bound the number of attempts.
  4. 4. How does redo differ from next?

    redo restarts the iteration without advancing and without re-checking a loop condition, so it needs a guard to avoid an endless loop.
  5. 5. Which is the best way to leave three nested loops once a value is found?

    break only leaves the innermost iterator. A method with return, or catch/throw, unwinds several levels cleanly.

Summary

  • next ends the current block call or loop pass; in a block its value becomes the block's result.
  • break ends the iterator method that took the block and gives that call its value; a lambda's break and return just leave the lambda, and an orphaned proc raises LocalJumpError.
  • redo restarts the current iteration without advancing; guard it with a counter or avoid it.
  • retry lives in rescue and re-runs the protected code; bound the attempts and add backoff.
  • loop ends quietly on StopIteration; to leave nested loops use a method with return, or catch/throw.

Next: Methods