I'd say thatI think 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 aretend to be more clear.
In this case, it's a pity Ruby hasn't gotwe can use the abstraction Enumerable#map_by (a group_by
variation where you can control both the grouping function and the accumulated values), then you could and 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.