SupremeA SupremeA - 1 month ago 5
Ruby Question

How to add amounts from an array of arrays

I have an array of arrays like so...

a1 = [[9, -1811.4], [8, 959.86], [7, -385], [6, -1731.39], [5, 806.78], [4, 2191.65]]


I need to get the average of the 2nd items(the amounts) from the total array.

So add -1811.4,959.86,-385,-1731.39,806.78 divided by the count (6)

I have tried...

a1.inject{ |month, amount| amount }.to_f / a1.size


This is not right and I cant see what I need to do

Answer
a1.map(&:last).inject(:+) / a1.size.to_f
#=> 5.0833333333332575

Steps:

# 1. select last elements
a1.map(&:last)
#=> [-1811.4, 959.86, -385, -1731.39, 806.78, 2191.65]
# 2. sum them up
a1.map(&:last).inject(:+)
#=> 30.499999999999545
# 3. divide by the size of a1
a1.map(&:last).inject(:+) / a1.size.to_f
#5.0833333333332575
Comments