Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array reverse_each_with_index

Tags:

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?

like image 265
user2125770 Avatar asked Apr 01 '13 05:04

user2125770


People also ask

What does Reverse_each do in Ruby?

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.

How do you iterate through reverse order in Ruby?

You can use "unshift" method to iterate and add items to new "reversed" array.


1 Answers

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
like image 180
Bue Grønlund Avatar answered Sep 18 '22 08:09

Bue Grønlund