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.
1fornumin(0..5)2putsnum3end
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.
1foriin(1..3)2puts"Outer loop: i = "+i.to_s3forkin(1..4)4puts"Inner loop: k = "+k.to_s5end6end
If you execute the program presented, you will see that the outer loop is displayed three times. However, ...
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