ActiveSupport Enumerable#group_by

Hi, all.

I want to add new method in Enumerable module.

It is the method that calculate together the hash in the array.

  1. Unify the hash with the same hash for particular key (base key)

  2. Calculate the total for the values of another key (target key)

  3. 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

Hi Wataru,

Methods are generally added to activesupportwhen useful to support the other rails functionality. There are an infinite number of potentially useful methods to add and it doesn’t make sense for rails to include them all.

-Ben

Hi Ben,

Thank you for replying. If I implement the good methods, I can try again.

Regards,
Ben

2016年8月2日火曜日 10時54分11秒 UTC+9 Ben Woosley: