Module: Enumerable

Defined in:
lib/datasumz/core_extensions/enumerable/sd.rb,
lib/datasumz/core_extensions/enumerable/sum.rb,
lib/datasumz/core_extensions/enumerable/mean.rb,
lib/datasumz/core_extensions/enumerable/median.rb

Instance Method Summary collapse

Instance Method Details

#mean(default = nil) ⇒ Object

Calculates the mean of a numeric collection.

Examples:

[1, 2, 3, 4, 5].mean #=> 3
[].mean #=> nil
[].mean(0) #=> 0

Parameters:

  • default (Object) (defaults to: nil)

    an optional default return value if there are no elements. It is nil by default.

Returns:

  • The mean of the elements or the default value if there are no elements.



16
17
18
19
# File 'lib/datasumz/core_extensions/enumerable/mean.rb', line 16

def mean(default = nil)
  coll_size = to_a.size
  coll_size > 0 ? reduce(&:+) / coll_size.to_f : default
end

#median(default = nil) ⇒ Object



5
6
7
8
# File 'lib/datasumz/core_extensions/enumerable/median.rb', line 5

def median(default = nil)
  sorted = sort
  (sorted[(length - 1) / 2] + sorted[length / 2]) / 2.0
end

#sdObject

def variance



10
11
12
# File 'lib/datasumz/core_extensions/enumerable/sd.rb', line 10

def sd
  Math.sqrt(variance)
end

#sum(identify = nil) ⇒ Object

Sums up elements of a collection by invoking their ‘+` method.

Examples:

[1, 2, 3, 4, 5].sum #=> 15
["a", "b", "c"].sum #=> "abc"
[].sum #=> nil
[].sum(0) #=> 0

Parameters:

  • default (Object)

    an optional default return value if there are no elements. It is nil by default.

Returns:

  • The sum of the elements or the default value if there are no elements.



17
18
19
# File 'lib/datasumz/core_extensions/enumerable/sum.rb', line 17

def sum(identify = nil)
  reduce(&:+) || default
end

#varianceObject



5
6
7
8
# File 'lib/datasumz/core_extensions/enumerable/sd.rb', line 5

def variance
  sum = inject(0) { |accum, i| accum + (i - mean) ** 2}
  sum/(length - 1).to_f
end