In this tutorial, we will learn about for loops in Ruby. We will cover the basics of iterative execution using for loops.
In Ruby, a for loop is used to iterate over a collection of items, and execute a block of code for each element in the collection.
The syntax for the for loop in Ruby is:
for item in iterable do
# Code block to be executed
end
The for loop iterates over each item in the iterable object (such as an array or a range) and executes the code block for each item. We can access the item
inside the for loop.
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 have seen how to use a For loop to iterate over a range of numbers. using this we can find the factorial of a number, by iterating the for loop from 1 to the given number.
For example,
n = 5
factorial = 1
for i in 1..n
factorial *= i
end
puts "Factorial of #{n} is #{factorial}"
Factorial of 5 is 120
We have seen how to use a For loop to iterate over a range of numbers. using this we can accumulate the numbers in a sum, by iterating the for loop from 1 to the given number.
For example,
arr = [1, 2, 3, 4, 5]
sum = 0
for num in arr
sum += num
end
puts "Sum of the elements in the array is #{sum}"
Sum of the elements in the array is 15