The Spaghetti Refactory Established 2015

Enumerating in Ruby like a BOSS

The other day I wanted to run collect on an array, but I needed the indexes of the elements collected as well. Essentially, I wanted an array of hashes with the index as the key and the element as the value. I could have sloppily hacked together something like this:

my_new_array = []
my_array.each_with_index do |element, index|
my_new_array << { index => element }
end
return my_new_array

When doing some Googling, I found out that Ruby allows enumerator method chaining - in other words, I can take an array and run something like this:

my_array.each_with_index.collect do |element, index|
{ index => element }
end

I love my collect method, so anytime I can use it, I will. And apparently, in Ruby, any enumerable can be called on any other enumerable.

Tags