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 what you want to accumulate), 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.