In this tutorial, we will learn about different types of loops in Ruby. We will cover the basics of for, while, and until loops.
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.
There are three types of loops in Ruby. They are:
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
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
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
We can use a For loop to iterate over a range of numbers.
For example,
for i in 1..10
print i, " "
end
1 2 3 4 5 6 7 8 9 10
We can use a For loop to iterate over a range of numbers.
For example,
i
and initialize it to 1.i = 1
while i <= 5 do
puts i
i += 1
end
1 2 3 4 5
We can use an Until loop to iterate over numbers from 1 to n.
For example,
i
and initialize it to 1.i = 1
until i > 5 do
puts i
i += 1
end
1 2 3 4 5