I would like to use something like reverse_each_with_index
on an array.
Example:
array.reverse_each_with_index do |node,index|
puts node
puts index
end
I see that Ruby has each_with_index
but it doesn’t seem to have an opposite. Is there another way to do this?
Ruby | Array reverse_each() function Array#reverse_each() : reverse_each() is a Array class method which traverses self in reverse order. Return: traverses self in reverse order.
You can use "unshift" method to iterate and add items to new "reversed" array.
If you want the real index of the element in the array you can do this
['Seriously', 'Chunky', 'Bacon'].to_enum.with_index.reverse_each do |word, index|
puts "index #{index}: #{word}"
end
Output:
index 2: Bacon
index 1: Chunky
index 0: Seriously
You can also define your own reverse_each_with_index method
class Array
def reverse_each_with_index &block
to_enum.with_index.reverse_each &block
end
end
['Seriously', 'Chunky', 'Bacon'].reverse_each_with_index do |word, index|
puts "index #{index}: #{word}"
end
An optimized version
class Array
def reverse_each_with_index &block
(0...length).reverse_each do |i|
block.call self[i], i
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With