-5

I've assigned these rows to hashes:

other_id: 1,amount: 9290,id: 1
other_id: 2,amount: 2262,id: 1
other_id: 3,amount: 9588,id: 2
other_id: 4,amount: 1634,id: 2

How do I add together the amount values for a specific id, so for id: 1, I need the total = 9290 + 2262?

Even better, if I had a large collection of these, how would I write code so that it would find the id number with the maximum value of total if total is the sum of all amount instances for a specific id number?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
purry
  • 62
  • 1
  • 10
  • What do `other_id` and `id` mean? Are they related, and is either of them the key for the hash? – Milo P Mar 18 '16 at 20:48
  • 2
    Please write your code in a pseudo code and explain in more details. Neither your code nor your question make any sense – Maged Makled Mar 18 '16 at 20:53
  • Say each row is a hash and I have all rows in an array. other_id doesn't matter to me. I just want to look at amount and id and make sure it adds each amount for the same id OR make a code that looks through the whole file and recognizes which id number has the greatest total of amounts. – purry Mar 18 '16 at 21:10
  • Welcome to Stack Overflow. Please read "[ask]" including the links at the bottom. We need to see an example of your effort: That means seeing code or evidence of your searching for solutions. As is it looks like you want us to write it for you, which is off-topic. http://meta.stackoverflow.com/q/261592/128421 – the Tin Man Mar 18 '16 at 22:11

1 Answers1

0

Assuming your input looks like this:

array = [{id: 1, amount: 9290, other_id: 123}, {id: 1, amount: 1234, other_id: 30}, {id: 2, amount: 4444, other_id: 456}]

Q1

specific_id = 1 # or whatever you are looking for
sum = array.inject(0) do |sum, hash|
  sum += hash[:amount] if hash[:id] == specific_id
  sum
end

Q2 part 1: calculate the sums per id

sums = array.inject(Hash.new(0)) do |sums, hash|
  sums[hash[:id]] += hash[:amount]
  sums
end

Q2 part 2: find id/sum for max sum

max = sums.inject(sums.first) do |max, pair|
  pair.last > max.last ? pair : max
end
Pascal
  • 8,464
  • 1
  • 20
  • 31
  • Rather than rely on `inject` for this, look at [`each_with_object`](http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_with_object). It results in cleaner code because you don't have to return a value at the end of the block. – the Tin Man Mar 18 '16 at 22:13
  • Usually i prefer each_with_object as well. But IMHO it's not a good match here because you can only alter the object, not re-assign in the block. Would make first and last piece of code less straightforward. The second piece of code would looked better though. But i chose to use the same method in all three parts for consistency. – Pascal Mar 19 '16 at 08:29