To iterate over an array in Ruby, you can use methods like each
or for
loops.
In this example,
numbers
with some values.each
method to iterate over each element of the array and print the elements.numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
puts num
end
1 2 3 4 5
In this example,
fruits
with some values.for
loop to iterate over each element of the array and print the elements.fruits = ["apple", "banana", "cherry"]
for fruit in fruits
puts fruit
end
apple banana cherry
In this tutorial, we learned How to Iterate Over an Array in Ruby language with well detailed examples.