Alternative flashcard solution

Ok, first flashcard on “Mastering enumerable, Part I” inquires to turn array of strings into the hash of string lengths with corresponding strings as key values. The solution is:

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

And I think map with Hash[] would be more intention revealing:

def string_lengths(strings)
  Hash[strings.map { |string| [string, string.length] }]
end

One goal of the flashcard is to introduce people to inject (a surprisingly-unknown method), but I like your solution too!

I recently inherited a codebase with lots of this style of hash building and when running it through Rubocop, it was suggested to instead use each_with_object. I hadn’t heard of each_with_object before so I looked it up and found this nice article Better Hash Injection using each_with_object - CustomInk Technology Blog

Needless to say, I followed Rubocop’s advice and did the refactoring!