As a beginner programer, one of the things you might find challenging is understanding the while loop statement. This may seem confusing at first but we can reassure you that you’re not the first to feel discomfort with this concept, nor will you be the last. In other words, how you’re feeling towards while loop statements right now is completely normal!
Our goal today is help you strengthen your core foundations of iterating through an array using the while loop statement in the Ruby programming language.
We will cover the below topics:
- Understanding the Output We Want
- Manual Iteration
- While Loop Statement
- While Loop Syntax (Line By Line)
- Applying a While Loop Statement to an Array
Assuming that you’re very familiar with the syntax of an array, i.e. elements, indices, etc., we’re going to jump right in and focus on better understanding our while loop statement!
Understanding the Output We Want
Given the following array:
In this example, we set our array, “array” equal to four elements, the integers 1, 2, 3, and 4.
What we want to do with this information is simple. We want Ruby print out each element in our array on our console like the below:
The question is… how do we do that?
We could do a manual iteration by typing in every index in a puts statement such as the below:
This works, but it’s not really efficient.
What if you had an array with over 100 elements to print out? Would you want to manually iterate another 96 more elements? Sure, we could copy and paste multiple lines, but then we’d still need to edit each index to , , , … all the way through index . What about if you had over a 1,000 elements? Would you still want to manually iterate through that array?
This is where the while loop statement comes in handy.
While Loop Statement
Before we utilize this tool with our array, we first need to understand what requirements are needed to execute a while loop statement or its syntax.
Given the example:
We would have the following printed in our console:
If you’re wondering how this happened, we’re here to break it down with you!
While Loop Syntax (Line By Line)
Let’s take a look at our code line by line.
We set a variable i equal to 0. We’ll use this variable to check against our condition.
Note that we are able to name our variable to anything we want (i.e. t, index, num, etc.) and set it equal to any number we want to start with.
We declared our while statement, gave our i variable a condition to be less than 5, and the code followed after the do will be executed as long as the i variable holds true against the condition.
Pause… what does that actually mean??
This could be where one of your challenges with while loops appear. One reason being that it’s just one line of code that does a lot of work for you. But not to worry! Let’s walk through everything step by step.
In line 1, we set our i variable equal to 0. Great! We’re going to do just that:
In line 2, we then set our i variable with a condition to be less than 5. Okay, so let’s check against that: Is 0 less than 5? This isn’t a trick question ;) The answer is yes, 0 is less than 5! Let’s take note of that:
Next, still in line 2, we then established that as long as i variable is true against the condition, our code followed after do will be executed. Let’s take a look at the code we want to execute.
Here, we’re telling Ruby to print the string “Consider this!” on our console.
Earlier, we confirmed that with i = 0, it is indeed less than 5, holding true against our condition. Because this statement is true, Ruby will print the string “Consider this!” on our console:
So far so good, we got Ruby to do what we want! But!!! We’re not done with our while loop syntax.
Here, we’re incrementing the i variable by one. Meaning we’re increasing the value of i from 0 to 1. This is one of the most important steps in executing our while loop syntax properly.
Without this line, our while loop statement would go back to the i variable, sees that our value of i is still equal to 0, goes through the process of checking it against our condition of i < 5, sees that it’s still true, executes our code puts “Consider this!” again! Then goes back to the i variable again and repeats the process and again and again, creating an infinite loop.
Line 4 helps us reach an end to our while loop statement. It will eventually set our i variable to a value that will return false when we check it against our condition. False statements against our condition will allow us to exit out of the loop and end the while loop statement.
What does that mean?
Let’s walk through the rest of the code with the rest of the values our i variable was set to:
Thus giving us the output:
end indicates the…well… end of our while loop statement.
So now the question, “How do we apply this in an array?”
Applying a While Loop Statement with an Array
Given the array from earlier:
And considering the output we want:
We can now apply our while loop statement in place of our indices from our manual input earlier:
Knowing that our i variable is set to an integer, rather than using four lines with the same puts array  code with each of the indices inserted per line, we can now write it once and use our i variable in place of the indices instead!
The below will be the code we want to execute in our while loop statement:
Okay, so now that we have our code we want to execute, let’s build the rest of the syntax!
We’ll need a variable for our starting point. In this example, since we want to iterate over an array , we know that the first index starts at 0. With that being said, we’re going to set an i variable equal to 0:
Next, we’ll want to declare our while loop statement with the while, do, end keywords:
Cool! Now we want to set a condition inside our while loop. Since we’re iterating through a given array, we want to make our condition dynamic — meaning we want to avoid hardcoding an integer in our condition since you could potentially iterate through an array with 100 or even 1,000 elements!
Taking that into consideration, we’re going to use the .length method in place of hard coding an integer. This way, our while loop will iterate all 0-3 indices in our given array, or all 0-99 indices with the array of 100 elements, or 0-9,999 indices with the array of 1,000 elements.
Anyway, let’s see what that looks like:
Great! But we’re still not done. We need one more piece in our syntax to avoid an infinite loop.
Remember, our while loop statement will always go back to the variable. From the variable, it then will check its value against the condition and continues to execute our code if it holds true and repeats this process until the statement returns false.
In order to avoid this, we must always instruct Ruby to either increment or decrement our i variable. In this instance, we’re going to increment i += 1:
Are we done? Let’s try running the full code:
Amazing! We got the output we wanted!
When we find ourselves in a challenging state, whether if it’s about a method, syntax, concept, logic, etc., we find it best to take a step back, breathe and reassure ourselves that we’re probably not the first nor the last to experience the emotion towards that topic. In other words, there’s someone out there that can relate to what you’re going through!
Here, we experienced that in better understanding the while loop statement, we:
- Identified our desired output
- Broke down each step in our while loop syntax
- Visualized what each step was accomplishing by manually checking everything line by line
- Applied our understandings with an array
Sometimes all we need is that one extra step — whether if it’s reassuring ourselves that we’re not alone, breaking down the syntax, visualizing each code line by line, etc. — in order to overcome our challenges!