From: "David A. Black" Date: 2007-08-24T22:33:30+09:00 Subject: Re: Combining Array Elements Hi -- On Fri, 24 Aug 2007, Jeremy Wells wrote: > gregarican wrote: >> I have an array that I would like to combine elements. Here's a sample >> array: >> >> [["Value A", "Value B", 3], ["Value A", "Value C", 2],["Value A", >> Value B", 1]] >> >> What I would like to do is find the elements where the first two items >> are the same and then combine the third. The resulting array would >> consist of: >> >> [["Value A", "Value B", 4],["Value A", "Value C", 2]] >> >> This is something that is out in left field in terms of how I've used >> arrays in the past. Anyone know of a quick bit of script I can whip up >> that will suit the task? >> > new_array = array.collect{|v| [v[0],v[1], a.select{|b| b[0] == v[0] && b[1] ^^^^^^^^ You mean array.select, I think. > == v[1] }.inject(0){|m,b| m + b.last}]}.uniq This is just a cosmetic change, but you could do: new_array = array.map {|v,w| [v,w, array.select {|b,c| b == v && c == w }.inject(0){|m,b| m + b.last}]}.uniq or even: new_array = array.map {|v,w| [v,w, array.select {|b,c| [b,c] == [v,w] }.inject(0){|m,b| m + b.last}]}.uniq David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)