At the very beginning of our career as software developers we tend to think that we can copy and paste code when we want a kind of behavior where we need something to repeat. Let me explain. If we want to repeat the sentence “Hello World!” for 10 times what's your first thought about how to solve it? Probably copy and pasting the whole sentence 10 times and the job is done. But what happens if we want to repeat that very same sentence 100, 1.000 or 10.000 times? A little harder isn't it? This leads us to the firs concept of the present blog post: Loops
Loops allows you to:
- - Go over a list of things & work with each individual element
- - Repeat something a set number of times
- - Keep a program running until the user wants to stop it
Loops
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.
Previously in the blog post called
Control Flow and Conditionals in Ruby we’ve learnt about conditionals. What is the conditional in our previous examples? The conditional is the number of loops: 10, 100, 1.000 or 10.000. The technical number for this conditional is Counter.
Counters allow us to execute the very same instruction for a number of a given times. So the condition is something like this:
- - Execute instructions until counter reach the 10th loop
- - Execute instructions until counter reach the 100th loop
- - Execute instructions until counter reach the 1.000th loop
- - Execute instructions until counter reach the 10.000th loop
According to this, it is easy to figure out that we have to repeat something given the counter we received for our user.
The Times Loop
In Ruby we can use the Times Loop which helps us to achieve this goal: “Repeat an instruction a set number of times”. Let’s do it.
Inside your IRB console type:
2.6.8 :001 > 10.times do
2.6.8 :002 > puts "Hello World!"
2.6.8 :003?> end
As we can see, we give the conditional 10.times and then inside the block do/end we have the string we want to print.
While Loop
This loop is a bit more complicated to understand and to define, so grab a cup of coffee and we can start explaining it!
The example we’re going to do is the same as the Times Loop example, where we repeated the sentence "Hello World!" 10 times. While loop syntax is similar to this:
i = 0 # initialize counter
while <conditional>
# 1. code that will be repeated while the condition is true
# 2. update the counter
end
Code above is what we call pseudo-code and helps us to explain what will happen with the real code. Now let's do the real example
i = 0 # initialize counter
while i < 10
# 1. code that will be repeated while the condition is true
puts "Hello World!"
# 2. update the counter
i = i + 1
end
Then let’s execute the code in the console to see the output
As we can see we’ve now repeated the sentence 10 times. The difference is the method we used = While
Let’s evaluate line by line
- - First line helps us to initialize the counter in zero. It’s so important to remember that this initializer needs to be outside the while loop. Why is that? Because if we place the initializer inside the while loop it will become part of the loop. Code is read line by line (from top to down) for the interpreter
- - Second line we’ve the while keyword and then the conditional. First time the conditional is evaluated, it could be translated like this
- First loop: 0 < 10 (which is true) so it executes what's inside the while loop
- - Next line of code prints the sentence once we are inside the while loop
- - Last but not least we update the counter. This is a critical step because the initial counter was set to be 0, and if we evaluate the conditional 0 < 10 it will always be true. So we need a way to update the counter and next time evaluate 1 < 10
- Second loop: 1 < 10 (which is true) so it executes what's inside the while loop
- Third loop: 2 < 10 (which is true) so it executes what's inside the while loop
- Fourth loop: 1 < 10 (which is true) so it executes what's inside the while loop
- …
- Last loop: 10 < 10 (which is false) so we exit the while loop
This is obviously a bit more complicated than Times Loop in Ruby, however is less limited than it. Let’s see why:
- Time Loop in ruby is limited by an integer condition, because the .times method just receives an Integer value. So the only conditional to evaluate here is the Integer, not other complex conditionals
- While loop can work with Integers and any other data type, and because of this we can have complex conditionals which can make our code robust and adaptable to our own problem.
Later in other exercises we can talk about this other options that we have with While loops
Infinite Loop
We have to take care about infinite loops, because as the name suggests, the conditional evaluated by the While loop can always be true. If that's the case the resources of the machine will be consumed rapidly and probably you will need to reset it. Which examples do we have here to explain this concept?
Note: to stop an infinite loop in your console just type CTRL+C
2.6.8 :001 > while true
2.6.8 :002?> puts "Hello World!"
2.6.8 :003?> end
As you can see, the sentence will be executed infinitely because the while loop is always evaluating to true. Same thing can happen is we don’t update the counter in the previous exercise
At the end of the while loop we didn’t update the counter, which means that the conditional always be true because 0 < 10 is true. Let’s test the result in the console. (remember to stop it with CTRL + C)
What will happen in the opposite site, where the conditional is never met
2.6.8 :001 > while false
2.6.8 :002?> puts "Hello World!"
2.6.8 :003?> end
It will return nil, because the while loop conditional is never met and executed.
I think that we learnt a lot with this post, later we’ll be doing more exercises, but for now is clear Time Loops and While Loops syntax and theory
Thanks for reading!
DanielM