Skip to content

Instantly share code, notes, and snippets.

@mindplace
Created March 20, 2016 03:46
Show Gist options
  • Select an option

  • Save mindplace/28490483c0d9f30db413 to your computer and use it in GitHub Desktop.

Select an option

Save mindplace/28490483c0d9f30db413 to your computer and use it in GitHub Desktop.
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