From: "Peña, Botp" Date: 2007-08-25T15:29:33+09:00 Subject: Re: Combining Array Elements From: Stefan Rusterholz [mailto:apeiros@gmx.net] # What makes me slightly sad is that all those examples try to # squeeze as much as possible into a single statement. Frankly, # in my opinion the resulting code is horrible to read again a few # months later. # array = [["Value A", "Value B", 3], ["Value A", "Value C", # 2],["Value A", "Value B", 1]] # groups = array.group_by { |element| element.first(2) } # result = groups.map { |key, values| # values.map! { |a,b,c| c } # key+[values.sum] # } glad you mention group_by :) anyone who's been making reports and transposing rows/columns can see its value. i think we can still squeeze to one line and still be readable, now that you mention group_by. note that i modified your sum. i like passing what i want to add. eg, > a => [["A", "B", 3], ["A", "C", 2], ["A", "B", 1]] > a.group_by{|x|x.first(2)} => {["A", "B"]=>[["A", "B", 3], ["A", "B", 1]], ["A", "C"]=>[["A", "C", 2]]} basically, we get the key, then merge the sum of the last elements thus, > a.group_by{|x|x.first(2)}.map{|x,y| x< [["A", "B", 4], ["A", "C", 2]] or > a.group_by{|x|x.first(2)}.map{|x,y| x+[y.sum{|z|z.last}]} => [["A", "B", 4], ["A", "C", 2]] or just use plain inject instead of sum > a.group_by{|x|x.first(2)}.map{|x,y|x< [["A", "B", 4], ["A", "C", 2]] kind regards -botp