Learn Ruby the Hard Way – Exercise 33 While Loops

Here is my work for Exercise 32.

Exercise 32 code
Exercise 32 code
Exercise 32 output
Exercise 32 output

In the exercise code, Zed Shaw asks if you remember the other two ways from the previous exercise. I have written two other ways to print out the numbers array in comments.

Study Drills
1. Convert this while-loop to a function that you can call, and replace 6 in the test (i < 6) with a variable.

Rewriting the loop into a function.
Rewriting the loop into a function.

2. Use this function to rewrite the script to try different numbers.
On line 17 and line 18, I call the function using 3 and 6.
3. Add another variable to the function arguments that you can pass in that lets you change the + 1 on line 8 so you can change how much it increments by.

The function takes two parameters, an increment value and an upper limit number.
The function takes two parameters, an increment value and an upper limit number.

3. Rewrite the script again to use this function to see what effect that has.

Incrementing by 2 with an upper limit of 3, only 0 and 2 are added to the numbers array.
Incrementing by 2 with an upper limit of 3, only 0 and 2 are added to the numbers array.

4. Write it to use for-loops and (0 .. 6) range operator. Do you need the incrementor in the middle anymore? What happens if you do not get rid of it?

Rewritten script with for loop and range operator.
Rewritten script with for loop and range operator.

An increment operation is not needed because the for loop automatically increments through the values of the range operator.

Rewritten script output.
Rewritten script output.

Note that the upper_limit parameter in this function indicates the number that WILL NOT be added to the numbers array. If we wanted the upper_limit number to be the last element added to the array, we would type (0..upper_limit) on line 4 instead. The numbers would then be 0, 1, 2, 3, 4, 5, 6.

Summary
This exercise introduces while loops. It also shows that some while loops can be rewritten into for loops. When writing a while loop, it is important to check the condition (and its changes) throughout the loop so that you do not end up with an endless loop.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s