Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Bozhidar Batsov
committed
Sep 9, 2013
1 parent
bb77aff
commit 3f28be2
Showing
4 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |