ActiveSupport Enumerable#group_by

45 views
Skip to first unread message

Wataru Kikuchi

unread,
Aug 1, 2016, 2:36:48 PM8/1/16
to Ruby on Rails: Core
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

Ben Woosley

unread,
Aug 1, 2016, 9:54:11 PM8/1/16
to rubyonra...@googlegroups.com
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
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-co...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

Wataru Kikuchi

unread,
Aug 5, 2016, 11:25:26 PM8/5/16
to Ruby on Rails: Core
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:
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-core+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages