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"?
0
1
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]
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
Source: https://habr.com/ru/post/1489925/More articles:AutoCad Leader Color Change - vbaHow to Report Click-Jacking Abuses Using Facebook Social Connections - facebookDifference between grid rendering and its point cloud - 3dRefresh div after form Submit Mootools 1.1 to Mootools 1.4.1 - javascriptTranslating a page using Javascript - javascriptVisual Studio 2012 - several commands in command line arguments - visual-studio-2012How to avoid cutting corners with A * pathfinding? - c #Check if two iterators come from the same object - c ++Quoting through a file and deleting certain lines - bashHow to run custom datapikers from javascript in FirefoxOS? - firefoxAll Articles