Module: Riveter::CoreExtensions::ArrayExtensions
Instance Method Summary collapse
-
#average ⇒ Object
average of a set of numbers.
- #cumulative_sum ⇒ Object
-
#find_each_with_order(&block) ⇒ Object
(also: #find_each)
make compatible with an ActiveRelation.
-
#nil_sum(identity = nil, &block) ⇒ Object
pure genious.
-
#round(places) ⇒ Object
rounds each items to the specified number of places.
-
#standard_deviation ⇒ Object
standard deviation of an array of numbers.
-
#to_hash_for(&block) ⇒ Object
returns a hash of the items, indexed by the given items attribute.
-
#variance ⇒ Object
variance of a set of numbers.
Instance Method Details
#average ⇒ Object
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_sum ⇒ Object
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_deviation ⇒ Object
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 |
#variance ⇒ Object
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 |