0

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

2 Answers 2

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

3 Comments

Does this method turn negatives to positives when adding?
@SupremeA it does not. It just sums it. Do you need to sum absolute values?
yep I see now Thanks!
2

One pass through a1 is sufficient.

a1.reduce(0) { |tot, (_,b)| tot + b }/a1.size.to_f
  #=> 5.0833333333332575

.to_f allows a1 to contain only integer values.

The steps:

tot = a1.reduce(0) { |tot, (_,b)| tot + b }
  #=> 30.499999999999545 
n = a1.size.to_f
  #=> 6.0 
tot/n
  #=> 5.0833333333332575 

3 Comments

Just another option, we can also use .fdiv(a1.size) instead of /a1.size.to_f.
@sagarpandya82, I'd never heard of Numeric#fdiv. Thanks for the tip.
Was also considering adding a inject option, but it took more letters to type then my original one, so i dropped it :)

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.