Ruby Enumerable is amazing

Katrina unleashed this gem of a document on us today: Focus on Collections

Now, documentation doesn’t always get me amped up but I enjoyed reading this document so much I tweeted about it.

In my previous ruby work I’ve implemented, by hand, many of these methods (map, any?, find) simply because I didn’t know Enumerable was so powerful.

Map: like each but with fewer lines

Map (or collect) takes you from

numbers = [1,2,3,4]
doubles = []
numbers.each do |number|
  doubles.push(number*2)
end

doubles => [2, 4, 6, 8] 

to

numbers = [1,2,3,4]
doubles = numbers.map {|number| number*2}

doubles => [2, 4, 6, 8] 

The take away?

It’s nothing all that crazy but reading the docs can really payoff.