Loops and Iterators

We discussed Ruby blocks and iterators back in Chapter 4, Collections, Blocks, and Iterators. In this section, we’ll talk about all of Ruby’s looping constructs in more depth.

Loops

Ruby has primitive built-in looping constructs, separate from the iterator constructs we’ve already seen.

The most basic loop of all that Ruby provides is a built-in iterator method called loop:

 loop​ ​do
 # block ...
 end

The loop iterator calls the associated block forever (or at least until you break out of the loop, but you’ll have to read ahead to find out how to do that).

The while loop executes its body zero or more times as long as its condition is true. For example, this idiom reads until the input is exhausted, assigning each ...

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.