Module: Enumerable

Defined in:
lib/summarytools/core_extensions/enumerable/sd.rb,
lib/summarytools/core_extensions/enumerable/sum.rb,
lib/summarytools/core_extensions/enumerable/mean.rb,
lib/summarytools/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.



14
15
16
17
# File 'lib/summarytools/core_extensions/enumerable/mean.rb', line 14

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

#median(default = nil) ⇒ Object



3
4
5
6
# File 'lib/summarytools/core_extensions/enumerable/median.rb', line 3

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

#sdObject

def variance



8
9
10
# File 'lib/summarytools/core_extensions/enumerable/sd.rb', line 8

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.



15
16
17
# File 'lib/summarytools/core_extensions/enumerable/sum.rb', line 15

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

#varianceObject



3
4
5
6
# File 'lib/summarytools/core_extensions/enumerable/sd.rb', line 3

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