tags:

views:

48

answers:

3
[[1, 20],[2,30],[1,5],[4,5]]

In ruby how does one go through this array and add the second element if the first is the same with and output such as:

[[1, 25],[2,30],[4,5]]
+2  A: 

A solution in Ruby:

L = [[1, 20],[2,30],[1,5],[4,5]]
d = {}
L.each{|k,v| d[k] = (d[k]||0) + v}

A solution in Python:

L = [[1, 20],[2,30],[1,5],[4,5]]
d = {}
for k,v in L: 
    d[k] = d.get(k,0) + v
Olivier
I wish I knew python but I don't and I asked for ruby
Sam
I answered you in Ruby!
Olivier
oh terribly sorry. didn't look like ruby code to me.
Sam
BTW - which to you like better? Ruby or Python
Sam
+1  A: 

You can do this (warning, the output is a bit garbled, you may want to convert to array):

myArray = [[1, 20],[2,30],[1,5],[4,5]]
outputHash = {}
myArray.each do |values|
    outputHash[values[0]] = outputHash[values[0]].to_i + values[1]
end
puts outputHash
TZer0
+4  A: 

If order isn't important, inserting the pairs into a hash, adding if the key already exists, and then flattening the hash back into an array is a neat way. In irb:

>> a = [[1, 20],[2,30],[1,5],[4,5]]

=> [[1, 20], [2, 30], [1, 5], [4, 5]]

>> a.inject(Hash.new(0)) { |h, p| h[p[0]] += p[1]; h }.to_a

=> [[1, 25], [2, 30], [4, 5]]
Nefrubyr
BTW: In Ruby 1.9, hash keys are guaranteed to be in insertion order.
Jörg W Mittag