Hi, all.
I want to add new method in Enumerable module.
It is the method that calculate together the hash in the array.
-
Unify the hash with the same hash for particular key (base key)
-
Calculate the total for the values of another key (target key)
-
And return value an array of hash with a base key and the target key and their values
For example:
ary = [ {name: ‘morita’, money: 1000, count: 1}, {name: ‘morita’, money: 1500, count: 1}, {name: ‘tanaka’, money: 2000, count: 1}, {name: ‘suzuki’, money: 5000, count: 1}, {name: ‘suzuki’, money: 5000, count: 1}, {name: ‘fukawa’, money: 9000, count: 1}, {name: ‘suzuki’, money: 8000, count: 1}, {name: ‘akashi’, money: 1000, count: 1} ] module Enumerable
def uniq_merge(keys = , values = )
self.group_by { |i| keys.map { |key| i[key] } }
.map { |k, v|
v[1..-1].each { |x| values.each { |y| v[0][y] += x[y] } }
v[0]
}
end
end
result = ary.uniq_merge([:name], [:money, :count]) require ‘pp’ pp result
=>
[ {name: “morita”, money: 2500, count: 2}, {name: “tanaka”, money: 2000, count: 1}, {name: “suzuki”, money: 18000, count: 3}, {name: “fukawa”, money: 9000, count: 1}, {name: “akashi”, money: 1000, count: 1} ]
Regards,
Kikuchi