From: Yossef Mendelssohn Date: 2007-08-24T22:34:58+09:00 Subject: Re: Combining Array Elements On Aug 24, 7:50 am, 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? irb(main):001:0> orig_array = [["Value A", "Value B", 3], ["Value A", "Value C", 2],["Value A", "Value B", 1]] => [["Value A", "Value B", 3], ["Value A", "Value C", 2], ["Value A", "Value B", 1]] irb(main):002:0> hash = Hash.new(0) => {} irb(main):003:0> orig_array.each { |elem| hash[ elem[0,2] ] += elem[2] } => [["Value A", "Value B", 3], ["Value A", "Value C", 2], ["Value A", "Value B", 1]] irb(main):004:0> hash.collect { |k, v| k + [v] } => [["Value A", "Value C", 2], ["Value A", "Value B", 4]] or, more concisely irb(main):001:0> orig_array = [["Value A", "Value B", 3], ["Value A", "Value C", 2],["Value A", "Value B", 1]] => [["Value A", "Value B", 3], ["Value A", "Value C", 2], ["Value A", "Value B", 1]] irb(main):002:0> orig_array.inject(Hash.new(0)) { |hash, elem| hash[ elem[0,2] ] += elem[2]; hash }.collect { |k, v| k + [v] } => [["Value A", "Value C", 2], ["Value A", "Value B", 4]] -- -yossef