Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if a program has fixed number of iterations.
Ruby for loop will execute once for each element in expression.
Syntax:
for variable [, variable ...] in expression [do]
code
end
Ruby for loop using range
Example:
a = gets.chomp.to_i
for i in 1..a do
puts i
end
Output:

Ruby for loop using array
Example:
x = ["Blue", "Red", "Green", "Yellow", "White"]
for i in x do
puts i
end
Output:

Leave a Reply