This section documents Ruby’s simple looping statements:
for. Ruby also includes the ability to define
custom looping constructs known as iterators.
Iterators (see Iterators and Enumerable Objects) are probably more commonly
used than Ruby’s built-in looping statements; they are documented later
in this chapter.
Ruby’s basic looping statements are
until. They execute a chunk of code
while a certain condition is true, or
until the condition becomes true. For
x = 10 # Initialize a loop counter variable while x >= 0 do # Loop while x is greater than or equal to 0 puts x # Print out the value of x x = x - 1 # Subtract 1 from x end # The loop ends here # Count back up to 10 using an until loop x = 0 # Start at 0 (instead of -1) until x > 10 do # Loop until x is greater than 10 puts x x = x + 1 end # Loop ends here
The loop condition is the Boolean expression that appears
do keywords. The
loop body is the Ruby code that appears between the
do and the
while loop evaluates its condition. If the
value is anything other than
nil, it executes its body, and
then loops to evaluate its condition again. In this way, the body is
executed repeatedly, zero or more times, while the condition remains true (or, more
until loop is the
reverse. The condition is tested and the body is executed if the
condition evaluates to
nil. This means that the ...