← Back to Upcase

Alternative flashcard solution


(Charushin Roman) #1

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

(Ben Orenstein) #2

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


(Jon Kinney) #3

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 http://technology.customink.com/blog/2014/10/14/better-hash-injection-using-each-with-object/

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