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}
]
--
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.
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.