- Read Tutorial
- Watch Guide Video
We're going to start this section on loops out with one of the most primitive ways of iterating through a collection, the while loop.
While loops are rarely used in Ruby development, however they will offer a solid foundation for the other tools that we can use to work with sets of data. And if you're coming from another programming language you are most likely already familiar with while loops.
While Loop Code Example
The code for a basic
while loop is below:
i = 0 while i < 10 puts "Hey there" i += 1 end
Let's walk through the steps for building a
while loop in Ruby:
- We have to create a variable that will work as a counter and set it equal to
- Then we declare the conditional which you can read as:
while i is less than 10... continue looping.
- Inside the loop we place the code we want executed each time the loop runs.
- We increment our loop variable
1with each iteration. This is required to prevent an infinite loop from occurring. An infinite loop is what happens when you forget to tell the loop when it can stop and it will eventually crash the program.
- Lastly we supply the keyword
endto designate where the loop code ends.
If you run this code, you can see the following output:
If you count, you can see it printed the string
Hey there 10 times.
This output may sometimes be confusing because we asked the code to print a message when
i was less than 10, so why did it print it out 10 times?
Before I explain this behavior, let's update the code slight by using the
<= operator (which stands for less than or equal to):
i = 0 while i <= 10 puts "Hey there" i += 1 end
If you notice, the message was printed 11 times.
This is because the value of
i started at
0. So, it ran the first time and was incremented after iterating through the loop. It's important whenever using a while loop to understand what criteria will cause it to end or you may end up with slightly different results that you wanted.
One thing to keep in mind when using
while loops is to always increment the value of the loop variable. Because if you don't, the value of
i will always be
0, and the loop will simply continue to run until the program crashes.
Also, if you notice, Ruby does not have an increment operator like
++, which can be found in other languages. So when you want to increment a value by one in Ruby you need to do it manually, like this:
i = i + 1
Or you can alternatively use the shortcut syntax that I used in the
i += 1
devCamp note: There is nothing special with using the
i variable name. You could use any variable name that you want as long as the name matches the other parts of the program.