Skip to content

Commit 1275ada

Browse files
committed
Merge pull request #21 from Fryguy/block_for_element_counts
Add ability to pass a transformation block to element_counts
2 parents b37c82b + 2f3667d commit 1275ada

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

lib/more_core_extensions/core_ext/array/element_counts.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
module MoreCoreExtensions
22
module ArrayElementCounts
3-
# Returns a Hash of each element to the count of those elements.
3+
# Returns a Hash of each element to the count of those elements. Optionally
4+
# pass a block to count by a different criteria.
45
#
56
# [1, 2, 3, 1, 3, 1].counts # => {1 => 3, 2 => 1, 3 => 2}
7+
# %w(a aa aaa a aaa a).counts { |i| i.length } # => {1 => 3, 2 => 1, 3 => 2}
8+
#
69
def element_counts
7-
each_with_object(Hash.new(0)) { |i, h| h[i] += 1 }
10+
each_with_object(Hash.new(0)) do |i, h|
11+
key = block_given? ? yield(i) : i
12+
h[key] += 1
13+
end
814
end
915
end
1016
end
Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
11
describe Array do
2-
it "#element_counts" do
3-
expect([].element_counts).to eq({})
4-
expect([1].element_counts).to eq({1 => 1})
5-
expect([nil].element_counts).to eq({nil => 1})
6-
expect([1, 2, 3, 1, 3, 1].element_counts).to eq({1 => 3, 2 => 1, 3 => 2})
2+
describe "#element_counts" do
3+
it "without a block" do
4+
expect([].element_counts).to eq({})
5+
expect([1].element_counts).to eq({1 => 1})
6+
expect([nil].element_counts).to eq({nil => 1})
7+
expect([1, 2, 3, 1, 3, 1].element_counts).to eq({1 => 3, 2 => 1, 3 => 2})
8+
end
9+
10+
it "with a block" do
11+
expect([].element_counts(&:size)).to eq({})
12+
expect(%w(a).element_counts(&:size)).to eq({1 => 1})
13+
expect(%w(a aa aaa a aaa a).element_counts(&:size)).to eq({1 => 3, 2 => 1, 3 => 2})
14+
end
715
end
816
end

0 commit comments

Comments
 (0)