1
[[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]]

3 Answers 3

4

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

BTW: In Ruby 1.9, hash keys are guaranteed to be in insertion order.
2

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

2 Comments

I wish I knew python but I don't and I asked for ruby
BTW - which to you like better? Ruby or Python
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.