Skip to content

Commit

Permalink
Merge pull request #7 from fuadsaud/enumerable-frequency
Browse files Browse the repository at this point in the history
Add Enumerable#frequency
  • Loading branch information
bbatsov committed Aug 29, 2013
2 parents d4dd528 + a910c93 commit 9091159
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -27,6 +27,7 @@ Or install it yourself as:
* [Enumerable](http://rdoc.info/github/bbatsov/powerpack/Enumerable)
* [#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)
* [#frequencies](http://rdoc.info/github/bbatsov/powerpack/Enumerable#frequencies-instance_method)
* [#several?](http://rdoc.info/github/bbatsov/powerpack/Enumerable#several?-instance_method)
* [#sproduct](http://rdoc.info/github/bbatsov/powerpack/Enumerable#sproduct?-instance_method)
* [#sum](http://rdoc.info/github/bbatsov/powerpack/Enumerable#sum-instance_method)
Expand Down
1 change: 1 addition & 0 deletions lib/powerpack/enumerable.rb
@@ -1,5 +1,6 @@
require_relative 'enumerable/drop_last'
require_relative 'enumerable/drop_last_while'
require_relative 'enumerable/frequencies'
require_relative 'enumerable/several'
require_relative 'enumerable/sproduct'
require_relative 'enumerable/sum'
Expand Down
19 changes: 19 additions & 0 deletions lib/powerpack/enumerable/frequencies.rb
@@ -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
20 changes: 20 additions & 0 deletions spec/powerpack/enumerable/frequencies_spec.rb
@@ -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

0 comments on commit 9091159

Please sign in to comment.