Created
March 20, 2016 03:46
-
-
Save mindplace/28490483c0d9f30db413 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module ExtraArrayMethods | |
| def average(*nums) | |
| nums.dup.inject(:+) / nums.length | |
| end | |
| def median(*nums) | |
| nums = nums.uniq.sort | |
| if nums.length < 4 | |
| return nums[0] if nums.length == 1 | |
| if nums.length == 2 | |
| med = nums.dup.inject(:+).to_f / nums.length | |
| if med == med.round | |
| return med.round | |
| else return med | |
| end | |
| end | |
| return nums[1] | |
| end | |
| median(*nums[1..-2]) | |
| end | |
| def mode(*nums) | |
| frequencies = Hash.new(0) | |
| nums.sort.each{|num| frequencies[num] += 1} | |
| modes = frequencies.select{|k, v| v == frequencies.values.max} | |
| modes.keys.length == 1 ? modes.keys[0] : modes.keys | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment