Here’s an quick Ruby method I stumbled upon to help find the average of an array of floats. Much time and lines of code were saved. Less code is better code.

Try it for yourself.

$ irb --simple-prompt
arr = [59.0, 60.0, 85.0, 86.0, 89.0, 64.0, 55.0, 60.0, 81.0, 170.0, 122.0, 304.0, 106.0, 147.0, 318.0, 170.0, 298.0, 145.0, 331.0, 421.0, 472.0, 271.0, 198.0, 473.0, 349.0, 505.0, 323.0, 529.0, 555.0, 350.0, 471.0, 357.0, 362.0, 359.0, 655.0, 591.0, 165.0, 303.0, 744.0, 110.0, 626.0, 88.0, 828.0, 865.0, 838.0, 106.0, 233.0, 838.0, 601.0, 166.0, 474.0, 118.0, 108.0, 444.0, 950.0, 981.0, 55.0, 934.0, 834.0, 895.0, 59.0, 80.0, 57.0, 795.0, 741.0, 78.0, 54.0, 80.0, 599.0, 60.0, 53.0, 53.0, 60.0, 61.0, 718.0, 687.0, 85.0, 82.0, 566.0, 56.0, 83.0, 56.0, 77.0, 476.0, 55.0, 441.0, 234.0, 178.0, 119.0, 55.0, 55.0, 64.0, 56.0, 58.0, 56.0, 54.0, 84.0, 58.0, 58.0, 59.0, 60.0, 57.0, 60.0, 58.0, 82.0, 77.0, 135.0, 236.0, 116.0, 266.0, 269.0, 238.0, 147.0, 142.0, 327.0, 264.0, 360.0, 262.0, 386.0, 414.0, 413.0, 381.0, 417.0, 295.0, 414.0, 473.0, 446.0, 324.0, 504.0, 298.0, 185.0, 540.0, 188.0, 538.0, 574.0, 355.0, 571.0, 543.0, 568.0, 720.0, 599.0, 817.0, 509.0, 920.0, 462.0, 400.0, 55.0, 982.0, 90.0, 58.0, 52.0, 982.0, 507.0, 58.0, 475.0, 952.0, 59.0, 145.0, 534.0, 954.0, 942.0, 52.0, 77.0, 62.0, 862.0, 600.0, 472.0, 534.0, 889.0, 866.0, 816.0, 170.0, 113.0, 108.0, 81.0, 59.0, 51.0, 57.0, 91.0, 714.0, 60.0, 624.0, 60.0, 596.0, 56.0, 57.0, 327.0, 206.0, 54.0, 58.0, 58.0, 59.0, 57.0, 58.0, 61.0]
arr.reduce(:+) / arr.length
# => 318.02564102564105

All we did was sum the floats in the array, then divided by the length of the array.