each_with_object

January 30, 2013

Ruby 1.9 introduced more than a few useful methods. I’ve been able to wring a lot of use out of Enumerable’s new method #each_with_object

Usage

In situations where you’d do something like the following:

array = %w(alpha bravo charlie delta)
results = []

array.each do |item|
  results << item.to_sym
end

results.reverse!

You can do something like this instead:

array = %w(alpha bravo charlie delta)

results = array.each_with_object([]) do |item, results|
  results << item.to_sym
end.reverse

This reduces lines of code while making the source more readable at the same time.