You can use group_by
to group the foos
array by :key
. However I would first downcase
the :key
value, since you want 'Bar'
and 'bar'
to end up in the same group.
# We first need to unify the keys of the hashes before we can start
# grouping. 'Bar' != 'bar' so they would be split up in two separate
# groups. Judging from the output you don't want this.
foos.each { |foo| foo[:key].downcase! }
# Now that all keys are downcased we can group based upon the value of
# the :key key.
grouped_foos = foos.group_by { |foo| foo[:key] }
# Now we need to map over the resulting hash and create a single result
# for each group.
grouped_foos.transform_values! do |foos|
# First I'll transform the structure of `foos`, from:
#
# [{a: 1, b: 2}, {a: 3, b: 4}]
#
# into:
#
# [[:a, 1], [:b, 2], [:a, 3], [:b, 4]]
#
tmp = foos.flat_map(&:to_a)
# Then I'll group the above structure based upon the first value in
# each array, simultaneously removing the first element. Resulting in:
#
# {a: [[1], [3]], b: [[2], [4]]}
#
tmp = tmp.group_by(&:shift)
# We now need to flatten the values by one level. Resulting in:
#
# {a: [1, 3], b: [2, 4]}
#
tmp.transform_values! { |values| values.flatten(1) }
# The next step is remove duplicate values. We currently have:
#
# {key: ['foo', 'foo'], value: [1, 1], revenue: [2, 4]}
#
# whereas we want:
#
# {key: ['foo'], value: [1], revenue: [2, 4]}
#
tmp.transform_values!(&:uniq)
# Lastly if the array only contains a single value we want to use the
# value instead of an array. Transforming the above structure into:
#
# {key: 'foo', value: 1, revenue: [2, 4]}
#
tmp.transform_values! { |head, *tail| tail.empty? ? head : [head, *tail] }
# Finally we need to return our new hash.
tmp
end
Combining the above steps we get the following result:
foos.each { |foo| foo[:key].downcase! }
grouped_foos = foos.group_by { |foo| foo[:key] }
grouped_foos.transform_values! do |foos|
foos.flat_map(&:to_a).group_by(&:shift)
.transform_values { |values| values.flatten(1).uniq }
.transform_values { |head, *tail| tail.empty? ? head : [head, *tail] }
end
If you don't want to modify the (capitalisation of the) original foos
structure you'll have to replace:
foos.each { |foo| foo[:key].downcase! }
# with
unified_keys = foos.map(&:dup).each { |foo| foo[:key] = foo[:key].downcase }
Then use the new unified_keys
structure from that point on.
The above solution produces the following result:
grouped_foos
#=> {"foo" =>{:key=>"foo", :value=>1, :revenue=>[2, 4]},
# "bar" =>{:key=>"bar", :value=>2, :revenue=>[7, 9]},
# "zampa"=>{:key=>"zampa", :value=>4, :revenue=>9}}
You can get the result you want by requesting the values of the grouped_foos
:
grouped_foos.values
#=> [{:key=>"foo", :value=>1, :revenue=>[2, 4]},
# {:key=>"bar", :value=>2, :revenue=>[7, 9]},
# {:key=>"zampa", :value=>4, :revenue=>9}]