liveBook · Manning

Until loop

As explained in The Well-Grounded Rubyist, Fourth Edition

The until keyword is a Ruby control-flow keyword that repeatedly executes a loop body until a condition becomes true.

Ruby’s until loop repeatedly executes a body while its condition is false, stopping when that condition becomes true. Its logic reverses while. section 6.2 section 6.2.2

Use until in several forms:

  • Place until before the body: the condition is tested first, so a true condition prevents any execution. section 6.2.2
  • Place until after a begin/end body: the body executes once before Ruby tests the condition. section 6.2.2
  • Use modifier syntax for a compact single statement, such as incrementing a value until it reaches a target. section 6.2.2

Counting to ten

n = 1 until n > 10 puts n n = n + 1 end The body prints and increments n while n > 10 is false; once n becomes 11, the loop stops. section 6.2.2

n = 1
until n > 10
  puts n
  n = n + 1
end

Inspect a runnable pre-block until loop that prints integers from 1 through 10. section 6.2.2

The placement difference matters: a pre-block until can execute zero times, whereas a post-block until always executes once. Even modifier loops may return nil when their condition is already true. section 6.2.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains pre-block, post-block, and modifier forms, including zero-versus-one execution, but defers exhaustive loop control.
Examples
Demonstrates counting from 1 to 10, modifier syntax, and pre-block versus post-block execution.
What it assumes
Assumes basic conditions, variables, incrementing, and Ruby blocks while demonstrating loop structure from concrete examples.
What you can do after
Apply until loops to repeat work until a condition becomes true, choosing pre-block or post-block evaluation deliberately.
How it connects
Contrasts until with while and relates both to begin/end blocks, loop, break, and next.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.