class Array

stuff for dealing with statistics

monkey patches Hash, Array, ActiveRecord::Base and ActiveRecord::Relation

Public Instance Methods

mean() click to toggle source
# File lib/crunchr/core_ext.rb, line 30
def mean
  (self.sum * 1.0) / self.count
end
median() click to toggle source
# File lib/crunchr/core_ext.rb, line 38
def median
  center = (self.count + (self.count % 2)) / 2
  list = self.sort

  self.count % 2 == 0 ?
   [ list[center - 1], list[center] ].mean :
   list[center - 1]
end
mode() click to toggle source
# File lib/crunchr/core_ext.rb, line 52
def mode
  counts = {}
  self.collect { |i| counts[i] ||= 0; counts[i] += 1 }
  counts.key(counts.values.sort.last)
end
range() click to toggle source
# File lib/crunchr/core_ext.rb, line 47
def range
  list = self.sort
  list.last - list.first
end
stddev() click to toggle source
# File lib/crunchr/core_ext.rb, line 34
def stddev
  Math.sqrt(self.collect{ |i| (i - self.mean) ** 2 }.sum) / Math.sqrt(self.count - 1)
end
sum() click to toggle source
# File lib/crunchr/core_ext.rb, line 26
def sum
  self.inject(0.0) { |s, i| (s += i) rescue s }
end
timed_interval(length, amount=1) click to toggle source

return an array of arrays where each inner array represents a period of time

Synopsis

timed_interval(:week, 2)   # two week periods
timed_interval(:month, 6)  # half year periods
timed_interval(:day, 1)    # per day

Prerequisites

The items in the list must respond_to interval_time and it must return something that responds to < or >

# File lib/crunchr/active_record.rb, line 19
def timed_interval(length, amount=1)
  list = self.sort_by(&:created_at)
  current = list.first.interval_time(length)


  records = []
  period  = []

  list.each do |record|
    if record.interval_time(length) > (current + (amount - 1))
      records << period
      period = []
      current = record.interval_time(length)
    end

    period << record
  end

  records
end