5.4 For Loops and Nested Loops

For Loops

A for loop takes a group of elements and runs the code within the loop for each element. This can be used to run a piece of code a certain number of times, or the operations can actually be based on the value. In Example 5-4, we see puts num is executed once for each value of num. That is, the loop will execute six times, and six lines with numbers 0 through 5 written one number per line will be generated. The range of values for num is defined by the construct 0..5 (see line 1), which represents all the integer values between 0 and 5 inclusive.

Example 5-4. For loop
    1 for num in (0..5)
    2 	puts num
    3 end

Nested Loops

A nested loop is a loop inside another loop. Although all kinds of loops can be nested, the most common nested loop involves for loops. These loops are particularly useful when displaying multidimensional data.

When using these loops, the first iteration of the first loop will initialize, followed by the second loop. The second loop will completely finish before the first loop moves on to its next iteration. If that sounds confusing, the example in Example 5-5 should help you understand the concept. Its corresponding flowchart is shown in Figure 5-4.

Example 5-5. Nested loop construct
    1 for i in (1..3)
    2 	puts "Outer loop: i = " + i.to_s
    3 for k in (1..4)
    4   puts "Inner loop: k = " + k.to_s
    5 	end
    6 end

If you execute the program presented, you will see that the outer loop is displayed three times. However, ...

Get Computer Science Programming Basics in Ruby 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.