Mastering Enumerable, Part 1

Flashcard 1 of 7

What Enumerable method is this code inadvertently reimplementing?

def string_lengths(strings)
  lengths = {}

  strings.each do |string|
    lengths[string] = string.length
  end

  lengths
end

# string_lengths(%w(ben chris mark)) =>
#   { "ben" => 3, "chris" => 5, "mark" => 4 }

The method is reimplementing inject.

In general, when you find yourself iterating over a collection and building up some sort of result (a single value, or a new collection), inject is what you want.

Here's the method rewritten:

def string_lengths(strings)
  strings.inject({}) do |lengths, string|
    lengths.merge(string => string.length)
  end
end

Watch Inject: Ruby's Fold from The Weekly Iteration.

Return to Flashcard Results