Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Ruby looping methods
2.1.
Simple Loop
2.2.
For Loops
2.3.
Times Loop
2.4.
upto loop
2.5.
downto loop
3.
Frequently Asked Questions
3.1.
What is Ruby?
3.2.
What is Looping in Ruby?
3.3.
What is the use of Range in Ruby?
3.4.
In Ruby, what does "!= nil" mean?
3.5.
How does the Until loop work in Ruby?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Looping with for and the Ruby Looping Methods

Author SAURABH ANAND
0 upvote

Introduction

We come across situations where we need to iterate through a series of data to be specific arrays. In the situation where making changes in all the elements of the array manually can take a lot of time, looping methods come into play and easily accomplish the task.

A loop is the repeated execution of a piece of code for a specific number of times or until a specific condition is met. we will cover While loops, do/while loops, and for loops.

In this blog, we will learn the concepts of various looping methods in Ruby. So without wasting any further let’s look at some Ruby looping methods.

Ruby looping methods

These are a few types of ruby looping methods.

Simple Loop

The loop method is the simplest way to create a loop in Ruby. The loop accepts a block, which is expressed by {...} or do... end. A loop will execute any code within the block unless you manually intervene with Ctrl + c or enter a break statement within the block, forcing the loop to end and the execution to continue after the loop.

Example

# Code for a simple loop
# An infinite loop
loop do
  puts "hit Ctrl + c to stop"
end
You can also try this code with Online Ruby Compiler
Run Code


Output

hit Ctrl + c to stop
hit Ctrl + c to stop
hit Ctrl + c to stop
^CTraceback (most recent call last):
        5: from main.rb:3:in `<main>'
        4: from main.rb:3:in `loop'
        3: from main.rb:4:in `block in <main>'
        2: from main.rb:4:in `puts'
        1: from main.rb:4:in `puts'
main.rb:4:in `write': Interrupt

For Loops

For loops are used in Ruby to loop over a collection of elements. Unlike a while loop, which can lead to an infinite loop if we are not careful, for loops have a definite end because they loop over a finite amount of elements. It starts with the reserved term for, then a variable, then the reserved word in, and finally a collection of components. We'll demonstrate this with an array and a range. A range is a Ruby special type that represents a set of elements. 1..3 is a range that includes the integers 1, 2, and 3.

Example

# Code for For Loop in Ruby using range
puts "enter end number:"
n = gets.chomp.to_i
puts "loop values:"
for i in 1..n do
  puts i
end
puts "Done!"
You can also try this code with Online Ruby Compiler
Run Code


Output

enter end number:
6
loop values
1
2
3
4
5
6
Done!


Let's look at another example using an array instead of a range.

Example

# Code for for loop using array
x = [11, 12, 13, 14, 15, 16]
for i in x do
  puts i
end
puts "Done!"
You can also try this code with Online Ruby Compiler
Run Code


Output

11
12
13
14
15
16
Done!

Times Loop

In Ruby, the times function returns all numbers from 0 to one less than the number itself. It loops across the specified block, sending increasing values from 0 to the limit. If no block is provided, an Enumerator is returned.

Syntax: (number).times

Example

# Code for times loop
4.times do
  |i| 
  puts("i = #{i}" )
end
You can also try this code with Online Ruby Compiler
Run Code


Output

i = 0
i = 1
i = 2
i = 3

Here, the loop is running 4 times as we have passed the whole block 4 times. Another thing to keep in mind is that we are not defining a method here. Rather, we're simply sending a block to the times method. We must always supply a block of instructions (code) to our loops. The block starts with do and ends with the end.

upto loop

In Ruby, the upward function retrieves all the numbers from a given number itself. It iterates across the provided block, sending increasing values from 1 to 2. If no block is provided, an Enumerator is returned.

Syntax: (number1).upto(number2)

Example

# Code for upto loop in ruby
0.upto(5) do
    | i |
    puts( i )
end
You can also try this code with Online Ruby Compiler
Run Code


Output

0
1
2
3
4
5

 

If no block is provided, an Enumerator is returned. Here is an example.

Example

# Code for upto loop
n1 = 0
puts n1.upto(5)
You can also try this code with Online Ruby Compiler
Run Code


Output

#<Enumerator:0x005559f55cce30>

downto loop

In Ruby, the downto() function returns all numbers less than the number and greater than the limit. It iterates across the specified block, passing decreasing values ranging from int down to and including limit. If no block is provided, an Enumerator is returned.

Syntax: (number).downto(limit)

Example

# Code for downto loop in ruby
5.downto(0) do
    | i |
    puts( i )
end
You can also try this code with Online Ruby Compiler
Run Code


Output

5
4
3
2
1
0


If no block is provided, an Enumerator is returned. Here is an example.

Example

# Code for downto loop
n1 = 5
puts n1.downto(-3)
You can also try this code with Online Ruby Compiler
Run Code


Output

#<Enumerator:0x0055f341cdcc30>

Frequently Asked Questions

What is Ruby?

Ruby is an open-source dynamic language with natural and easy-to-read/write syntax. Ruby is a careful balance language and a perfect blend of five different languages.

What is Looping in Ruby?

In Ruby, looping is a feature that allows a sequence of instructions or functions to be executed repeatedly when some of the conditions evaluate true or false.

What is the use of Range in Ruby?

Ranges are most commonly used to express a series. Sequences have a beginning, an end, and a method for producing subsequent values in the sequence.

In Ruby, what does "!= nil" mean?

Nil is a unique value in Ruby that represents the absence of any value. Nil is a NilClass object. Nothing or void is referred to as nil in Ruby.

How does the Until loop work in Ruby?

The statements or code in a Ruby Until loop are executed till the provided condition evaluates to true. It's basically the opposite of the while loop, which runs until the specified condition evaluates to false.

Conclusion

In this article, we have discussed the concept of Ruby looping methods. We started with the introduction of Ruby looping methods, examples of Ruby looping methods, and finally concluded with the types of Ruby looping methods

You can also check out our blogs on Ranges in RubyObject References in Ruby, and While and Until in Ruby.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your capacity in coding, you may check out the mock test series and participate in the contests hosted on the Coding Ninjas Studio website.

Happy Learning!

Coding Ninjas
Live masterclass