Loops
This section documents Ruby’s simple looping statements:
while, until, and 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.
while and until
Ruby’s basic looping statements are while and until. They execute a chunk of code
while a certain condition is true, or
until the condition becomes true. For
example:
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
between the while or until and do keywords. The
loop body is the Ruby code that appears between the do and the end keyword. The while loop evaluates its condition. If the
value is anything other than false
or 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
strictly, non-false and
non-nil).
The until loop is the
reverse. The condition is tested and the body is executed if the
condition evaluates to false or
nil. This means that the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access