The original array is
[
{\"id\"=>2, \"idx\"=>111, \"money\"=>\"4.00\", \"money1\"=>\"1.00\", \"order\"=>\"001\", \"order1\"=>\"1\"},
{\
I used this code
def aggregate(arr, group_fields, sum_fields, max_fields)
arr.group_by { |x| x.values_at(*group_fields) }.map {|key, hashes|
result = hashes[0].clone
max_fields.each { |k|
hashes.map! {|h| h.merge(h) { |k, v| Integer(v) rescue v }}
#hashes.map! { |h| h.each_pair { | k, v | h[k] = Integer(v) rescue v }}
result[k] = hashes.max_by { |h| h[k]}[k]
}
sum_fields.each { |k|
result[k] = hashes.inject(0) { |s, x| s + x[k].to_f }
}
result
}end
One thing not good is that to convert all fields to int (convert to int for comparison in case: "id"=>"12"
and "id"=>"2"
). Should convert max_fields only, but I dont think a solution yet. Code for convert is:
hashes.map! {|h| h.merge(h) { |k, v| Integer(v) rescue v }}
Or
hashes.map! { |h| h.each_pair { | k, v | h[k] = Integer(v) rescue v
So, its great if someone could solve this weak point.