The Spaghetti Refactory Established 2015

Enumerate in reverse with true indexes in Ruby

I had a problem one day where I had a list that I wanted to enumerate over, but I wanted to do it in reverse order. Easy peasy by just calling #reverse on the collection, right? Sure, except that I wanted the index as well. Oh, and I wanted the index to start with the last one instead of zero.

Now it's getting good.

I found this beauty on StackOverflow (thanks Bue Grønlund, whoever you are). To do a reverse each_with_index with the true index:

['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

Pretty nifty!

Tags