To iterate over an array in Ruby in reverse order, you can use the reverse_each
method or a for
loop starting from the last index to the first index.
In this example,
numbers
with some values.reverse_each
method to iterate over each element of the array in reverse order.numbers = [1, 2, 3, 4, 5]
numbers.reverse_each do |number|
puts number
end
5 4 3 2 1
In this example,
fruits
with some values.for
loop starting from the last index to iterate over each element of the array in reverse order.fruits = ["apple", "banana", "cherry"]
(fruits.length - 1).downto(0) do |i|
puts fruits[i]
end
cherry banana apple
In this tutorial, we learned How to Iterate Over an Array in Reverse Order in Ruby language with well detailed examples.