Replacing While loops in Ruby

Elizabeth
3 min readApr 10, 2020

--

A beginners guide to while loops and built in iteration methods.

In Ruby While loops are one of the ways we loop through a set of data in an array. A simple explanation is while a condition has not yet been met do something.

While a variable we set such as count, or index is less than a number, keep looping through the array. Looking at the below loop on line four, once count is equal to the length of our array, the looping process will stop on line four. Without a condition for our while loop we could end up with an infinite loop, which will break our program

The first example will output the values of the array through puts on line 4 without any filter or change to the number. The second example is using an if statement to on line 11 to check if the number is even. Only IF the number is even will it be given as an output through puts on line 12.

In both examples count is used to keep the loop going as long as the array. This is why we use array.size (same as array.length) as the value count needs to be less than. But could there be an easier way? Enter the. each method. .each is a built in ruby method which loops (or iterates) through an array the same way the above while loop does, without setting up a counter.

Lets try these examples again with .each:

Examples will have the same output as on top with much less code. We use number as a variable inside our || replacing array[count].

If we would like to shorten it even further we can replace do and end with {} also known as curly brackets.

To shorten our if statement to just one line we can even do:

Astute readers will notice we did not need an end for this kind of if statement!

To eliminate our if statement all together we can use .select. .select is similar to the while loops above as it loops or iterates through an array. The difference with. select is that it selects the values in that array that match the condition stated in our curly brackets.

OR

As you can see, .select iterates though our array and returns only the values that pass our conditional. Exactly the same as our if statements above with far less code.

--

--

Elizabeth
Elizabeth

No responses yet