Skip to content

Commit

Permalink
Merge pull request #21 from Fryguy/block_for_element_counts
Browse files Browse the repository at this point in the history
Add ability to pass a transformation block to element_counts
  • Loading branch information
bdunne committed Oct 15, 2015
2 parents b37c82b + 2f3667d commit 1275ada
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
10 changes: 8 additions & 2 deletions lib/more_core_extensions/core_ext/array/element_counts.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
module MoreCoreExtensions
module ArrayElementCounts
# Returns a Hash of each element to the count of those elements.
# Returns a Hash of each element to the count of those elements. Optionally
# pass a block to count by a different criteria.
#
# [1, 2, 3, 1, 3, 1].counts # => {1 => 3, 2 => 1, 3 => 2}
# %w(a aa aaa a aaa a).counts { |i| i.length } # => {1 => 3, 2 => 1, 3 => 2}
#
def element_counts
each_with_object(Hash.new(0)) { |i, h| h[i] += 1 }
each_with_object(Hash.new(0)) do |i, h|
key = block_given? ? yield(i) : i
h[key] += 1
end
end
end
end
Expand Down
18 changes: 13 additions & 5 deletions spec/core_ext/array/element_counts_spec.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
describe Array do
it "#element_counts" do
expect([].element_counts).to eq({})
expect([1].element_counts).to eq({1 => 1})
expect([nil].element_counts).to eq({nil => 1})
expect([1, 2, 3, 1, 3, 1].element_counts).to eq({1 => 3, 2 => 1, 3 => 2})
describe "#element_counts" do
it "without a block" do
expect([].element_counts).to eq({})
expect([1].element_counts).to eq({1 => 1})
expect([nil].element_counts).to eq({nil => 1})
expect([1, 2, 3, 1, 3, 1].element_counts).to eq({1 => 3, 2 => 1, 3 => 2})
end

it "with a block" do
expect([].element_counts(&:size)).to eq({})
expect(%w(a).element_counts(&:size)).to eq({1 => 1})
expect(%w(a aa aaa a aaa a).element_counts(&:size)).to eq({1 => 3, 2 => 1, 3 => 2})
end
end
end

0 comments on commit 1275ada

Please sign in to comment.