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
