Loops in Ruby

Learn via video courses
Topics Covered

Overview

In programming, loops are a fundamental concept used to repeat a certain task or set of instructions multiple times. Loops help automate repetitive tasks, reduce code length, and improve the program's efficiency. Like other programming languages, Ruby has several looping constructs which provide different ways of achieving iteration. This article will discuss the various types of loops in Ruby, their syntax and flow diagrams, and provide examples.

What are Loops in Ruby?

A loop is a control structure in Ruby that allows you to repeatedly execute a set of statements. There are several types of loops in Ruby, which are:

  1. Infinite Loops in Ruby using the loop keyword
  2. While Loops in Ruby
  3. Until Loops in Ruby
  4. Do..While Loops in Ruby
  5. For Loops in Ruby
  6. Iterators
    • each method
    • each_with_index method
  7. Times Loops in Ruby
  8. Range Loops in Ruby

Each of these loops has its syntax and usage, which is discussed in the subsequent headings.

Infinite Loop Using Loop Keyword in Ruby

The loop keyword creates an infinite loop in Ruby, which runs indefinitely until it is explicitly terminated. The following is the syntax for using the loop keyword in Ruby, followed by an example to show the use of the loop keyword in Ruby to create an infinite loop in Ruby:

Syntax:

Code:

The above program will print the sentence This is an infinite loop continuously until the program is terminated. To terminate loops in Ruby, we can incorporate a break-out condition in the code using the break keyword as follows:

Code:

Output:

In this example, the loop will continue to run until the count variable equals 5. The loop prints the current value of count plus one on each iteration and increments it by 1. The break statement: if count == 5 checks whether the count is equal to 5, and if it is, the break statement is executed, which exits the loop. When the count reaches 5, the loop finishes, and the message Loop finished! is printed.

While Loop in Ruby

The while loop in Ruby executes a set of statements as long as a given condition is true. The following is the syntax of the while loop in Ruby:

Syntax:

The condition is checked before the loop body is executed, and if it is true, the code in the loop body is executed. If the condition is false, the loop terminates. The following is the flow diagram that explains the while loop:

flow chart of while loop in Ruby

The following example prints numbers from 1 to 10 using a while loop in Ruby:

Code:

Output:

Note 📝:

You should be careful while using a while loop because if the condition is always true, the loop will become infinite, and the program will hang.

Until Loop in Ruby

The until loop is the opposite of the while loop. It executes a set of statements as long as a given condition is false. The following is the syntax of the until loops in Ruby:

Syntax:

The condition is checked before the loop body is executed, and if it is false, the code in the loop body is executed. If the condition is true, the loop terminates. The following is the flow diagram that explains the until loop:

flow chart of until loops in ruby

The following example prints numbers from 1 to 10 using an until loop in Ruby:

Code:

Output:

The until loop is generally preferred for expressing negative conditions. It provides a convenient substitute for using the not operator in the while loop condition. This is because using the until loop provides better readability and clarity to the code. It helps to avoid the negation operator and makes the logic more explicit and easier to understand.

When you want to repeat a block of code until a specific condition is met but the condition is negative, the until loop comes in handy. We will go through the following examples to support this point further:

Example 1: Prompting the user for input until a valid response is received

Until-loop version code:

In this example, we use an until loop to prompt the user for input until they provide a valid response (either yes or no). We use the logical OR (||) operator to combine the two conditions, which makes it easier to read and understand than using the not operator with a while loop.

The equivalent Ruby code, which uses the while loop and negation operator to implement the above logic, is as follows:

While-loop version code:

Example 2: Waiting for a resource to become available

Until-loop version code:

In this example, we use an until loop to wait for a resource to become available. We repeatedly check if the resource is available, and if not, we wait for 10 seconds before trying again. By using an until loop, we can clearly express the idea of keep waiting until the resource is available, which is more readable and easier to understand than using the not operator with a while loop.

The equivalent Ruby code, which uses the while loop and negation operator to implement the above logic, is as follows:

While-loop version code:

Example 3: Reversing a string

Until-loop version code:

In this example, we use an until loop to reverse a string. We repeatedly remove the last character of the string using the slice! method and append it to a new string (reversed) until the original string is empty. Using an until loop here makes the logic more clear and easier to understand than using the not operator with a while loop.

The equivalent Ruby code, which uses the while loop and negation operator to implement the above logic, is as follows:

While-loop version code:

Do While Loop in Ruby

The do..while loops in Ruby are almost like the while loop. The code inside the loop is executed at least one time before evaluating the boolean condition. This feature of do..while loops make them different from the while loops in Ruby. The while loop checks the boolean condition before executing the code inside the loop. The following is the syntax of the do..while loops in Ruby:

Syntax:

The code in the loop body is executed at least once, even if the condition is false. The following is the flow diagram that explains the do..while loop:

flow chart of do..while loops in ruby

The following example prints numbers from 1 to 10 using a do..while loops in Ruby:

Code:

Output:

The begin <code> end while <condition> is rejected by Ruby's author. This is because it makes the code less readable and less maintainable. The use of this syntax can make the code harder to understand for other developers who are not familiar with this syntax.

An alternative for this syntax, which uses the loop keyword to implement the do..while loop functionality, is as follows:

Syntax:

The following example prints the numbers from 1 to 10 using the loop method:

Code:

Output:

In this example, the loop will continue executing until i is greater than 10. At this point, the break statement will exit the loop.

Using a loop with a break statement can be a more readable and more flexible way to create loops in Ruby compared to using a do-while loop.

Ruby For Loop

The for loop in Ruby is used to iterate over a collection of objects. The following is the syntax of for loops in Ruby:

Syntax:

The expression can be any object that returns a collection, such as an array or a range. The loop body is executed once for each element in the collection, and the loop variable is set to the current element's value. The following is the flow diagram that explains the for loop:

flow chart of for loop in ruby

The following example prints numbers from 1 to 10 using a for loop in Ruby:

Code:

Output:

Note 📝:

The for loops can be easily replaced by an iterator in Ruby.

Iterators in Ruby

An iterator in Ruby is a method that processes a collection of objects one at a time. Iterators are more flexible and efficient than loops because they allow you to perform operations on each element of a collection without needing to manage a loop variable or worry about the length of the collection. Ruby has several built-in iterators, including each and each_with_index methods.

Each Method in Ruby

The each method in Ruby is an iterator that processes each element in a collection. The following is the syntax of the each method in Ruby:

Syntax:

The collection can be any object that returns a collection, such as an array or a hash. The code in the block is executed once for each element in the collection, and the variable is set to the current element's value.

Let us now understand this concept in a better way with the help of the following examples.

Example 1: Prints numbers from 1 to 10 using the each method in Ruby:

Code:

Output:

Example 2: Iterating over an array of strings using the each method in Ruby:

Code:

Output:

Example 3: Iterating over a hash of scores using the each method in Ruby:

Code:

Output:

In this example, we create a hash named scores that contains the scores achieved by a student in three subjects. We then iterate over the hash using the each method, printing each subject score and adding it to the total_score variable. At the end of the loop, we print the total score.

each_with_index Method in Ruby

The each_with_index method in Ruby is an iterator that processes each element in a collection and its index. The following is the syntax of the each_with_index method in Ruby:

Syntax:

The collection can be any object that returns a collection, such as an array or a hash. The code in the block is executed once for each element in the collection, the variable is set to the value of the current element, and the index is set to the current element's index.

Let us now understand this concept in a better way with the help of the following examples.

Example 1: Prints numbers from 1 to 10 using the each_with_index method in Ruby:

Code:

Output:

Example 2: Iterating over an array of strings using the each_with_index method in Ruby:

Code:

Output:

In this example, we use the each_with_index method to iterate over the fruits array, printing each fruit along with its index.

Example 3: Iterating over a hash of scores using the each_with_index method in Ruby:

Code:

Output:

In this example, we use the each_with_index method to iterate over the scores hash, printing each subject score along with its index.

Ruby Times Loop

The times loop in Ruby is a simple way to loop a fixed number of times. The following is the syntax of the times loop in Ruby:

Syntax:

The number is an integer that specifies the number of times to execute the loop body. The following example prints "Welcome to Scaler" ten times using the times loop:

Code:

Output:

Note 📝:

The times method is useful when executing a loop a fixed number of times.

Range Looping in Ruby

A range in Ruby is a set of values with a beginning and an end. Ranges can be used to generate sequences of numbers, characters, or other objects. The following is the syntax of Range looping in Ruby:

Syntax:

The start and end are the beginning and end of the range, respectively. The .. operator creates an inclusive range that includes the end value, and the ... operator creates an exclusive range that excludes the end value. The following example creates a range of numbers from 1 to 10:

Code:

Output:

Let us take another example to understand the range looping in a better way.

Code:

Output:

This code iterates over a range of characters from a to i (inclusive) using the each method. During each iteration, the current character of the range is assigned to the variable ch, and the puts method is called to output it to the console.

Therefore, this code will output the characters a, b, c, d, e, f, g, h, and i (one character per line) to the console in that order.

Advantages and Limitations of Loops in Ruby

Loops are a powerful feature of Ruby that allows you to execute code repeatedly. The following are some advantages of loops:

  • Loops are useful when executing a block of code multiple times.
  • Loops can be used to iterate over collections and perform operations on each element.
  • Loops can be used to create complex patterns and designs.

However, loops also have some limitations, as discussed below:

  • Loops can be inefficient if they are executed many times or over large collections.
  • Loops can be difficult to read and understand if they are not well-written or well-documented.
  • Loops can be prone to errors if they are not written correctly or if they have unexpected behavior.

It's important to use loops judiciously and to consider alternative solutions, such as iterators or recursion, when appropriate.

FAQs

Q: What is the difference between a while loop and an until loop in Ruby?

A: The while loop executes the code inside the loop as long as the condition is true, while the until loop executes the code inside the loop as long as the condition is false.

Q: Can I create an infinite loop using a for loop in Ruby?

A: Yes, you can create an infinite loop using a for loop in Ruby by omitting the start and end values or by using an infinite range. However, creating infinite loops is generally not a good practice, as they can cause your program to crash or hang.

Q: What is an iterator in Ruby?

A: An iterator in Ruby is a method that processes each element in a collection and performs an operation on it. Examples of iterators in Ruby include the each method and the map method.

Q: What is the difference between a loop and an iterator in Ruby?

A: A loop in Ruby executes a block of code repeatedly, while an iterator in Ruby processes each element in a collection and performs an operation on it. Loops are useful when executing a block of code multiple times. At the same time, iterators are useful when operating on each element in a collection.

Conclusion

  • Loops are a powerful feature of Ruby that allows you to execute code repeatedly.
  • Ruby provides a variety of loop constructs, including the while loop, the until loop, the for loop, and the times loop.
  • In addition, Ruby provides iterators such as the each method and the each_with_index method, which allow you to perform operations on collections.
  • You can write more efficient and expressive Ruby code using loops and iterators effectively.