Finding the Average Value in an Array in Ruby

2
13326

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’s Array class that returns the average value of the integers in the array.

Exercise File

Code 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.

2 COMMENTS

  1. `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.

  2. Beware the pitfalls of integer math:
    “`
    >> array = [1, 2]
    >> array.average
    #> 1
    “`
    You need to change the method to:
    inject(:+) / size.to_f

LEAVE A REPLY

Please enter your comment!
Please enter your name here