The while loop guide
We're going to start this section on loops with one of the most primitive ways of iterating through a collection: the while loop.
The 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. If you're coming from another programming language, you are most likely already familiar with the while loops.
The while loop code example
The following is the code for a basic while loop:
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
0. - Then we declare the conditional which you can read as: while
iis less than10, continue looping. - Inside the loop, we place the code we want to be executed each time the loop runs.
- We increment our
iloop variable by1with each iteration. This is required to prevent an infinite loop from occurring. An infinite...