Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/core-ext/array.rb
Overview
Extensions to Array to enable easier math
Instance Method Summary (collapse)
-
- (Object) mean
Calculates the arithmetic mean of values in the array.
-
- (Object) mean_squared
Calculates the mean squared error of values in the array.
-
- (Object) median
Calculates the median of values in the array.
-
- (Object) method_missing(method, *args, &block)
Allow [1,2,3].percentile_90, [1,2,3].percentile(75), etc.
-
- (Object) percentile(threshold)
Calculates the value of the upper percentile of values in the array.
-
- (Object) standard_dev
Calculates the standard deviatiation of values in the array.
-
- (Object) sum
Calculates the sum of values in the array.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
- (Object) method_missing(method, *args, &block)
Allow [1,2,3].percentile_90, [1,2,3].percentile(75), etc.
45 46 47 48 49 50 51 |
# File 'lib/core-ext/array.rb', line 45 def method_missing(method, *args, &block) if method.to_s =~ /^percentile_(.+)$/ percentile($1.to_i) else super end end |
Instance Method Details
- (Object) mean
Calculates the arithmetic mean of values in the array
10 11 12 |
# File 'lib/core-ext/array.rb', line 10 def mean self.sum.to_f / self.length end |
- (Object) mean_squared
Calculates the mean squared error of values in the array
34 35 36 37 |
# File 'lib/core-ext/array.rb', line 34 def mean_squared m = mean self.map{|v| (v-m)**2}.sum end |
- (Object) median
Calculates the median of values in the array
15 16 17 |
# File 'lib/core-ext/array.rb', line 15 def median self.sort[self.length/2] end |
- (Object) percentile(threshold)
Calculates the value of the upper percentile of values in the array. If only a single value is provided in the array, that is returned
22 23 24 25 26 27 28 29 30 31 |
# File 'lib/core-ext/array.rb', line 22 def percentile(threshold) if (count > 1) self.sort! # strip off the top 100-threshold threshold_index = (((100 - threshold).to_f / 100) * count).round self[0..-threshold_index].last else self.first end end |
- (Object) standard_dev
Calculates the standard deviatiation of values in the array
40 41 42 |
# File 'lib/core-ext/array.rb', line 40 def standard_dev (mean_squared/(count-1))**0.5 end |
- (Object) sum
Calculates the sum of values in the array
5 6 7 |
# File 'lib/core-ext/array.rb', line 5 def sum inject( nil ) { |sum,x| sum ? sum+x : x } end |