Permalink
Browse files

Add Enumerable#average

  • Loading branch information...
1 parent bb77aff commit 3f28be2e3ca91707c54db207ba5d648bb85adbc1 @bbatsov committed Sep 9, 2013
Showing with 41 additions and 0 deletions.
  1. +1 −0 README.md
  2. +1 −0 lib/powerpack/enumerable.rb
  3. +20 −0 lib/powerpack/enumerable/average.rb
  4. +19 −0 spec/powerpack/enumerable/average_spec.rb
View
@@ -25,6 +25,7 @@ Or install it yourself as:
* [#butlast](http://rdoc.info/github/bbatsov/powerpack/Array#butlast-instance_method)
* [#tail](http://rdoc.info/github/bbatsov/powerpack/Array#tail-instance_method)
* [Enumerable](http://rdoc.info/github/bbatsov/powerpack/Enumerable)
+ * [#average](http://rdoc.info/github/bbatsov/powerpack/Enumerable#average-instance_method)
* [#drop_last](http://rdoc.info/github/bbatsov/powerpack/Enumerable#drop_last-instance_method)
* [#drop_last_while](http://rdoc.info/github/bbatsov/powerpack/Enumerable#drop_last_while-instance_method)
* [#exactly?](http://rdoc.info/github/bbatsov/powerpack/Enumerable#exactly?-instance_method)
@@ -1,3 +1,4 @@
+require_relative 'enumerable/average'
require_relative 'enumerable/drop_last'
require_relative 'enumerable/drop_last_while'
require_relative 'enumerable/exactly'
@@ -0,0 +1,20 @@
+unless Enumerable.method_defined? :average
+ module Enumerable
+ # Calculates the average of a numeric collection.
+ #
+ # @param default [Object] an optional default return value if there are no elements.
+ # It's nil by default.
+ # @return The average of the elements or the default value if there are no
+ # elements.
+ #
+ # @example
+ # [1, 2, 3].average #=> 2
+ # [1, 2, 3, 4].average #=> 2.5
+ # [].average #=> nil
+ # [].average(0) #=> 0
+ def average(default = nil)
+ coll_size = size
+ coll_size > 0 ? reduce(&:+) / coll_size.to_f : default
+ end
+ end
+end
@@ -0,0 +1,19 @@
+require 'spec_helper'
+
+describe 'Enumerable#average' do
+ it 'calculates the average of an enum' do
+ expect((1..3).average).to eq(2)
+ end
+
+ it 'calculates the average of an array' do
+ expect([1, 2, 3, 4].average).to eq(2.5)
+ end
+
+ it 'returns nil when invoked on an empty collection' do
+ expect([].average).to be_nil
+ end
+
+ it 'returns default value when invoked on an empty collection' do
+ expect([].average(0)).to be_zero
+ end
+end

0 comments on commit 3f28be2

Please sign in to comment.