Ruby array reverse_each_with_index

ruby

Solution

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

Problem

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?

Original source