Back-end Engineering Articles

I write and talk about backend stuff like Ruby, Ruby On Rails, Databases, Testing, Architecture / Infrastructure / System Design, Cloud, DevOps, Backgroud Jobs, and more...

Twitter:
@daniel_moralesp

2019-05-10

Ruby Times Loop and While Loop

At the beginning of our career as software developers, we could copy and paste code when we needed something to repeat. Let me explain. If we want to repeat the sentence "Hello World!" 10 times, what's your first thought about solving it? 

Probably copy and paste 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 more complicated, isn't it? This leads us to the first concept of the present blog post: Loops.

Loops allow 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

A loop is a repeated sequence of instructions in computer programming until a specific condition is reached. 

The keyword to have in mind here is condition. Previously in the blog post called Control Flow and Conditionals in Ruby, we've learned about conditionals. What is the conditional in our previous example at the beginning of this article (about copy and paste)? The conditional is the number of loops: 10, 100, 1.000, or 10.000. The technical name for this type of conditional is Counter

Counters allow us to execute the same instruction several 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 from our user) until we reach the target number. 

The Times Loop

In Ruby, we can use the Times Loop, which helps us 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 Ruby block do/end, we have the string we want to print out.


While Loop

This loop is a bit more complicated to understand (and define), so grab a cup of coffee, and we can start explaining it!

As we explained here, we'll be using the text editor for the while loop, so please refer to the post.

We're going to do 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

The code above is what we call in programming "pseudo-code" and helps us explain what will happen with the actual 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 loop)

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

  • * In the second line, we have the while keyword and the conditional. The 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 again
  •  - Third loop: 2 < 10 (which is true), so it executes what's inside the while loop again
  •  - Fourth loop: 3 < 10 (which is true), so it executes what's inside the while loop again
  •  - It will continue until we reach...
  •  - 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, it is less limited. 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 instead, it 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 a vast amount of problems. 

Later in other exercises, we can discuss the alternatives with While loops. But, for now, let's go ahead. 

Infinite Loop

We have to take care of infinite loops because, as the name suggests, the conditional evaluated by the "While" loop can always be true. If that's the case, the machine's resources will be consumed rapidly, and probably you will need to cancel the execution or restart your device. 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 constantly evaluating to true. The same thing can happen if 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 on the opposite side, 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. 

We learned a lot with this post; later, we'll be doing more exercises, but for now, the basics of Time Loops and While Loops syntax and theory are clear.

Thanks for reading!
Daniel Morales