Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of several Ruby arrays

Tags:

arrays

ruby

I have three Ruby arrays:

[1, 2, 3, 4]
[2, 3, 4, 5]
[3, 4, 5, 6]

How can I take the average of all three numbers in position 0, then position 1, etc. and store them in a new array called 'Average'?

like image 739
bwobst Avatar asked Mar 24 '23 06:03

bwobst


1 Answers

a = [1, 2, 3, 4]
b = [2, 3, 4, 5]
c = [3, 4, 5, 6]

a.zip(b,c)
   # [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
.map {|array| array.reduce(:+) / array.size }
   # => [ 2,3,4,5]
like image 99
Jokester Avatar answered Apr 07 '23 07:04

Jokester