Skip to main content
6 of 7
added 26 characters in body
tokland
  • 11.1k
  • 1
  • 20
  • 25

I'd say that the refactor is barely readable, the first version is better. Anyway, if you use functional abstractions instead of doing a imperative processing from scratch, algorithms are more clear. In this case, it's a pity Ruby hasn't got Enumerable#map_by (a group_by variation where you can control both the grouping function and the accumulated values), then you could write:

require 'facets'

class Array
  def merge_hashes
    flat_map(&:to_a).map_by { |k, v| [k, v] }
  end 
end

Note that this snippet always returns an array as a value, instead of the scalar/list you have. Having mixed types in data structures is usually a bad idea, every single time you have to work with one of those values, you need to check whether it's an array or not, not nice. Here it's better just to use always an array.

tokland
  • 11.1k
  • 1
  • 20
  • 25