For Loop in Ruby
In this tutorial, we will learn about for loops in Ruby. We will cover the basics of iterative execution using for loops.
What is a For Loop
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.
Syntax
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.
Example 1: Printing Numbers from 1 to 10
We can use a For loop to iterate over a range of numbers.
For example,
- Write a For loop that iterates over a range of numbers: 1 to 10.
- 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
Example 2: Calculating the Factorial of a Number
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,
- Use a for loop to calculate the factorial of a number.
Ruby Program
n = 5
factorial = 1
for i in 1..n
factorial *= i
end
puts "Factorial of #{n} is #{factorial}"
Output
Factorial of 5 is 120
Example 3: Summing the Elements of an Array
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,
- Use a for loop to calculate the sum of the elements in an array.
Ruby Program
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}"
Output
Sum of the elements in the array is 15