Module: Riveter::CoreExtensions::ArrayExtensions

Extended by:
ActiveSupport::Concern
Included in:
Array
Defined in:
lib/riveter/core_extensions.rb

Instance Method Summary collapse

Instance Method Details

#averageObject

average of a set of numbers



57
58
59
# File 'lib/riveter/core_extensions.rb', line 57

def average
  self.sum / self.length.to_f
end

#cumulative_sumObject



38
39
40
41
# File 'lib/riveter/core_extensions.rb', line 38

def cumulative_sum
  sum = 0
  self.map {|x| sum += x}
end

#find_each_with_order(&block) ⇒ Object Also known as: find_each

make compatible with an ActiveRelation



93
94
95
# File 'lib/riveter/core_extensions.rb', line 93

def find_each_with_order(&block)
  self.each(&block) if block_given?
end

#nil_sum(identity = nil, &block) ⇒ Object

pure genious



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/riveter/core_extensions.rb', line 44

def nil_sum(identity = nil, &block)
  if block_given?
    self.inject(identity) {|sum, x|
      ((sum || 0) + (yield(x) || 0)) || sum
    }
  else
    self.inject(identity) {|sum, x|
      ((sum || 0) + (x || 0)) || sum
    }
  end
end

#round(places) ⇒ Object

rounds each items to the specified number of places



88
89
90
# File 'lib/riveter/core_extensions.rb', line 88

def round(places)
  self.collect {|x| x.round(places) }
end

#standard_deviationObject

standard deviation of an array of numbers



68
69
70
# File 'lib/riveter/core_extensions.rb', line 68

def standard_deviation
  Math.sqrt(self.variance)
end

#to_hash_for(&block) ⇒ Object

returns a hash of the items, indexed by the given items attribute



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/riveter/core_extensions.rb', line 73

def to_hash_for(&block)
  if block_given?
    self.inject({}) do |hash, record|
      hash[yield(record)] = record
      hash
    end
  else
    self.inject({}) do |hash, record|
      hash[record] = record
      hash
    end
  end
end

#varianceObject

variance of a set of numbers



62
63
64
65
# File 'lib/riveter/core_extensions.rb', line 62

def variance
  avg = self.average
  self.inject(0.0) {|acc, value| acc + ((value - avg)**2) } / (self.length.to_f - 1)
end