In this coding exercise you’ll learn how to open the Array class and add an average method that finds the average value from an array of integers.
Summary
Add an
average
method to Ruby’sArray
class that returns the average value of the integers in the array.
Exercise File
Exercise Description
Build a method that computes the average value of the elements in an Integer based array, and use monkey patching to add the method to the Array class.
Sample Method Call
[1, 2, 3].average # 2
Real World Usage
Running calculations on collections of data is a common requirement when it comes to Ruby development. Additionally, this exercise requires you to integrate monkey patching in order to add a method to a core Ruby class.
Solution
Can be found on the solutions branch on github.
`inject` method does not sum up all the elements in the Enumerable object. It combines them by applying a binary operation passed to it in the block. It will only sum if you instruct it to do so.
Beware the pitfalls of integer math:
“`
>> array = [1, 2]
>> array.average
#> 1
“`
You need to change the method to:
inject(:+) / size.to_f