Ruby Loops


Ruby Loops

In this tutorial, we will learn about different types of loops in Ruby. We will cover the basics of for, while, and until loops.


What is a Loop

A loop is a control flow statement that allows code to be executed repeatedly based on a condition. Ruby supports several types of loops, including for loops, while loops, and until loops.


Types of Loops in Ruby

There are three types of loops in Ruby. They are:

For Loop

A for loop is used to iterate over a range of values or elements in an array. The syntax for the for loop is:

for variable in range_or_array do
    # Code block to be executed
end

While Loop

A while loop is used to execute a block of code as long as a specified condition is true. The syntax for the while loop is:

while condition do
    # Code block to be executed
end

Until Loop

An until loop is used to execute a block of code as long as a specified condition is false. The syntax for the until loop is:

until condition do
    # Code block to be executed
end


Printing Numbers from 1 to 10 using For loop

We can use a For loop to iterate over a range of numbers.

For example,

  1. Write a For loop that iterates over a range of numbers: 1 to 10.
  2. Inside the For loop, print the number to output.

Ruby Program

for i in 1..10
    print i, " "
end

Output

1 2 3 4 5 6 7 8 9 10 


Printing Numbers from 1 to 5 using While Loop

We can use a For loop to iterate over a range of numbers.

For example,

  1. Declare a variable i and initialize it to 1.
  2. Use a while loop to print numbers from 1 to 5.
  3. Inside the While loop, print the number to output.

Ruby Program

i = 1
while i <= 5 do
    puts i
    i += 1
end

Output

1
2
3
4
5


Printing Numbers from 1 to 5 using Until Loop

We can use an Until loop to iterate over numbers from 1 to n.

For example,

  1. Declare a variable i and initialize it to 1.
  2. Use an until loop to print numbers from 1 to 5.
  3. Inside the Until loop, print the number to output.

Ruby Program

i = 1
until i > 5 do
    puts i
    i += 1
end

Output

1
2
3
4
5