3.2 Iteration

Got `for` loops?

Ruby, like most languages, has the all-time favourite for loop. Interestingly, nobody uses it much - but let's leave the alternatives for the next exercise. Here's how you use a for loop in Ruby. Just run the code below to print all the values in the array.

Example Code:

Output Window

Ok, your turn now. Copy the values less than 4 in the array stored in the source variable into the array in the destination variable.

Hint

You've already learned how to add elements to an array using the << and Array#push method. Combine this with an if check, testing if the number is less than 4.

Output Window

looping with `each`

Iteration is one of the most commonly cited examples of the usage of blocks in Ruby. The Array#each method accepts a block to which each element of the array is passed in turn. You will find that for loops are hardly ever used in Ruby, and Array#each and its siblings are the de-facto standard. We'll go into the relative merits of using each over for loops a little later once you've had some time to get familiar with it. Let's look at an example that prints all the values in an array.

Example Code:

Output Window

Ok, now let's try the same thing we did with the for loop earlier - copy the values less than 4 in the array stored in the source variable to the array in the destination variable.

Hint

You've already learned how to add elements to an array using the << and Array#push method. Combine this with an if check, testing if the number is less than 4.

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2024 by Sidu Ponnappa and Jasim A Basheer