For Loops in Ruby

Loops are a fundamental concept in any programming language. They allow us to execute a specific action continuously as long as a specified condition is true.

Ruby also offers the concept of loops that can perform similar actions. However, each loop method takes a different approach, and the purpose of the loop dictates its efficiency.

This quick guide will walk you through Ruby’s most common types of loops, including the while loop, for loop, and do while loop.

The While Loop

Let us start with the while loop because it will lay a logical foundation to implement other loop methods.

Ruby’s while loop helps test a condition and perform an action while that condition is true. The specified condition is tested at the beginning of the loop and should return either a Boolean true or Boolean false.

While the condition is true, the block inside the while loop is executed continuously and terminates once the condition is false.

The most common use of the while loop is when the number of program iterations is undetermined. For example, a loop that continuously asks the user for a password can run once or an infinite number of times.

The general syntax to implement a while loop in Ruby is:

while [condition] do
    # executeme

We start by calling the while keyword, which opens the loop block.

Next, we specify the condition for which the loop checks followed by the do keyword.

Inside the block, we add all the targeted code we wish to execute.

Finally, we close the loop by using the end keyword.

Ruby While Loop Example

Let us implement a simple example to illustrate how we can use a while loop. In this case, a simple countdown will suffice.

x = 60
while x > 0
    x -= 1
    puts "#{x} seconds remaining"

In the above example, we create a variable x and set the value to 60.

We then implement a loop to check if the value of x is greater than 0 and if true, put a message showing how many seconds are remaining.

To avoid the loop from running forever, we implement a decrement that deducts 1 for every iteration the loops run.

The For Loop

The next popular and useful loop method is a for loop. In some ways, it is similar to a while loop, but it implements the looping functionality differently.

The most common use of the for loop is when there’s a pre-determined number of iterations the loop needs to run.

For example, if the total number of password tries is less than 5, keep asking for a password; otherwise, block the account.

We also implement the condition for a for loop at the beginning of the loop.

The syntax for a for loop in Ruby is:

forvarin [expression] do
    # execute me

In the for-loop syntax above, we start by calling the for keyword, indicating the beginning of the for-loop block.

Next, we set the variable that acts as a reference for the condition. Think of it as the current trial in the password trial analogy.

We then use the in keyword, a Ruby pre-defined keyword commonly used in a for loop.

The next part is the expression; this is the range which to evaluate the variable. This can be a single range of values, an array to iterate through.

The next part is the do keyword that opens the for-loop block to add the code to perform while the condition is true.

Finally, we close the for loop with an end block.

Ruby For Loop Example

The following example illustrates how to use the for loop in Ruby.

foriin1..10 do
    puts i

In the example above, we define the variable i, which is just a placeholder for each item in the range of 1 to 10.

Ruby has two range operators: two dots (..) and three dots (…).

The two dots notation is known as an inclusive range operator. That means it will include the max value in the range. Think of it as less than or equal to.

The three dots notation—also called an exclusive operator—, does not include the max value in the operator. Similar to a less than.

If we run the code above, it should print the values from 1 and include 10 since we used the inclusive range.

To exclude 10 from the range of values, use the three-dot notation as:

foriin1..10 do
    puts i

Another example of using the for loops is to get items in an array. For example, suppose we have the following array:

frameworks = ["Ruby on Rails", "Angular", "VueJs", "Express", "Django", "React", "Laravel"]

By default, if we wanted to access an item in the array, we can use the index as:

puts frameworks[0]

If we wanted to access all items in the array, we would have to implement multiple repetitive lines.

puts frameworks[0]
puts frameworks[1]
puts frameworks[2]
puts frameworks[n]

Doing this is highly inefficient and moot when we do not know the total number of items in the array.

To solve this, we can implement a simple for loop:

frameworks = ["Ruby on Rails", "Angular", "VueJs", "Express", "Django", "React", "Laravel"]
for framework in frameworks do
    puts framework

The above item can be interpreted as: for each item in the items, print, the item.

Do While Loop

Another loop method is the do while loop. It is very similar to while loop but checks for the condition after executing the code block. Hence, even if the condition never evaluates to true, the loop will execute at least once.

The syntax for a do while loop in Ruby is:

loop do
    # run me once
break if [condition]

Ruby Do While Loop Example

The simple example below shows how to use a do while loop in Ruby:

loop do
    puts "Hi there!"
i = 10
    if i == 10

The loop will run once and exit.


In this tutorial, we discussed the basics of programming using loops in Ruby. Ruby has other loop methods that allow you to perform actions on other structures.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list