Page Content

Tutorials

What Are The Loops In Ruby With Practical Code Examples

Loops in Ruby

Loops are control structures that give a computer instructions to repeatedly run a series of statements. Both traditional looping statements (while, until, for) and, more frequently, extremely idiomatic looping techniques using iterators and code blocks are available in Ruby.

Traditional Looping Statements

Many other languages’ common loop constructs are supported by Ruby.

while loop

A block of code is executed by a while loop if the condition evaluates to true, which is any value other than false or nil. The body of the loop is run zero or more times while the condition is satisfied.

The optional keyword “do,” a semicolon, or a newline must come after the condition.

Code Example (while loop)

A counter variable that is greater than or equal to 0 is decremented in this example:

x = 10               # Initialize a loop counter variable
while x >= 0 do      # Loop while x is greater than or equal to 0
  puts x             #   Print out the value of x
  x = x - 1          #   Subtract 1 from x
end                  # The loop ends here

Output

10
9
8
7
6
5
4
3
2
1
0

A shorter sample illustrates iteration up to 5:

i = 0
while i < 5
  puts "Iteration ##{i}"
  i +=1
end

Output

Iteration #0
Iteration #1
Iteration #2
Iteration #3
Iteration #4

You can also read Arrays In Ruby: An Ordered Collections With Integer Indexes

until loop

When the conditional expression evaluates to false or nil, the until loop continues to run the code block until the condition is true. This is the logical opposite of the while loop. Simply negating the condition will convert any until loop to a while loop.

Code Example (until loop)

This illustration counts to ten until the requirement is satisfied:

x = 0                # Start at 0
until x > 10 do      # Loop until x is greater than 10
  puts x
  x = x + 1
end                  # Loop ends here

Output

0
1
2
3
4
5
6
7
8
9
10

for loop

An array or other enumerable object’s elements can be iterated through using the for loop, sometimes known as the for/in loop. This loop depends on an each iterator method in the underlying object.

One important difference is that local variables produced in a for loop’s body are still accessible after the loop ends, in contrast to local variables used in a standard block iterator (like each).

Code Example (for loop)

The for loop iterates through an array’s members, allocating each one to the loop variable “country”:

CountriesName = ["India", "Canada", "America", "Iraq"]
for country in CountriesName
    puts country
end

Output

India
Canada
America
Iraq

You can also read Hashes in Ruby: Understanding the Key-Value Data Structure

Looping Modifiers (Inline)

When used as modifiers for single expressions, the keywords while and until can be positioned after the expression they modify to provide a condensed form. The do and end keywords are omitted from this modification syntax.

Constraint: One restriction is that the modifier and the body expression must be on the same line.

Code Example (Using until modifier)

This example continually invokes the pop method on an array until it is empty by using the until modifier:

a = [35-37]
puts a.pop until a.empty?   # Pop elements from array until empty

Output

-2

In the event that the statement being changed contains a begin/end block, the code inside the block will always run at least once, independent of the initial boolean value, much like a do/while loop in C.

Iterators and Code Blocks (Idiomatic Ruby)

Iterators (methods called on objects) and code blocks (the body of the loop) are commonly used in idiomatic Ruby to do looping. The yield keyword is used by the iterator method to invoke the related code block, allowing for the intricate flow of control that makes this possible.

Curly braces ({}) are commonly used for single-line blocks, whereas do..end is frequently used for multi-line blocks.

Numeric Iterators

A number of iterator-based methods are defined by the Integer class:

times: Carries out the corresponding block a certain number of times, producing values that begin at 0.

upto: Iterates through each integer, starting with the receiver number and ending with the maximum number that was supplied as an argument.

downto: Moves in a loop from a bigger integer to a smaller one.

step: Iterates with a specified step size through a series of numbers.

Enumerable Iterators

Iteration-enabling techniques are defined by classes such as Array, Hash, and Range; these methods are frequently derived from the Enumerable module.

each: The most popular iterator, which forwards each collection element to the corresponding block.

map (or collect): Each element’s block is executed, and the return values are gathered into a new array.

inject: Used to invoke the block containing the next element of the enumerable object and an accumulated value in order to perform accumulation.

You can also read What Is Mean By Ranges In Ruby With Practical Code Examples

Altering Loop Control Flow

Ruby has specific statements to control how code is executed inside loops and iterators:

break: Transfers control right away from the nearest iterator or enclosing loop. When used in a loop, control returns right after the iterator or loop is invoked. Additionally, break has the ability to return a value for the loop expression.

next: Causes the iterator or loop to start the next iteration and stop the current one. When it is used inside a block, the block exits instantly, giving the iterator method back control.

redo: Restarting the current iteration from the beginning of the body is done without getting the next element or reevaluating the condition.

retry: The loop expression is reevaluated from the start to restart the entire loop or iterator. This can occasionally be used to fix input problems.

Code Example (Using next in an Iterator)

This example uses next to bypass elements that meet a condition:

(35..37).each do |item|
  next if item.even?
  puts "Item: #{item}"
end

Output

Item: 35
Item: 37

Code Example (Using break for return value)

This illustrates how to supply the loop expression’s result value via break:

even_value = for value in [35-37]
  break value if value.even?
end
puts "The first even value is: #{even_value}" 

Output

The first even value is: -2

Fibers and Continuations Additionally, Ruby has specialized control structures like fibers and continuations that can be leveraged to construct sophisticated iteration methods like goto statements or external iterators.

You can also read What Is Mean By Operators In Ruby, It’s Types With Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index