Average Ruby Arrays

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 at position 0 , then place 1 , etc. and save them in a new array named "Average"?

+4
source share
2 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] 
+7
source

Try the following:

 arr = ([1, 2, 3, 4] + [3, 4, 5, 6] + [2, 3, 4, 5]) arr.inject(0.0) { |sum, el| sum + el } / arr.size 

Concatenation can be done in several ways, depending on how you store your arrays.

Like syntactic sugar, you can do it like this:

 arr.inject(:+).to_f / arr.size 
0
source

Source: https://habr.com/ru/post/1489925/


All Articles