Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #7 from fuadsaud/enumerable-frequency
Add Enumerable#frequency
- Loading branch information
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,19 @@ | ||
unless Enumerable.method_defined? :frequencies | ||
module Enumerable | ||
# Counts the number of ocurrence of items in the enumberable. | ||
# | ||
# @return [Hash] in the format value => count | ||
# | ||
# @example | ||
# [].frequency # => {} | ||
# [1, :symbol, 'string', 3, :symbol, 1].frequency | ||
# #=> { 1 => 2, :symbol => 2, 'string' => 1, 3 => 1 } | ||
# | ||
# | ||
def frequencies | ||
inject(Hash.new(0)) do |a, e| | ||
a.tap { |acc| acc[e] += 1 } | ||
end | ||
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,20 @@ | ||
require 'spec_helper' | ||
|
||
describe 'Enumerable#frequencies' do | ||
context 'empty collection' do | ||
it 'evaluates to an empty hash' do | ||
expect([].frequencies).to eql({}) | ||
end | ||
end | ||
|
||
context 'populated collection' do | ||
it 'counts the number of ocurrences and returns a hash in the form value => count' do | ||
expect([1, 1, :symbol, 3, 1, :symbol, 'string'].frequencies).to eql( | ||
1 => 3, | ||
3 => 1, | ||
'string' => 1, | ||
:symbol => 2 | ||
) | ||
end | ||
end | ||
end |