Implement `Enumerable` tally from Ruby2.7.
MODIFY
mrbgems/mruby-enum-ext/mrblib/enum.rb
mrbgems/mruby-enum-ext/mrblib/enum.rb
@@ -839,4 +839,21 @@ module Enumerable
end
alias filter select
+
+ ##
+ # call-seq:
+ # enum.tally -> a_hash
+ #
+ # Tallys the collection. Returns a hash where the keys are the
+ # elements and the values are numbers of elements in the collection
+ # that correspond to the key.
+ #
+ # ["a", "b", "c", "b"].tally #=> {"a"=>1, "b"=>2, "c"=>1}
+ def tally
+ hash = {}
+ self.each do |x|
+ hash[x] = (hash[x]||0)+1
+ end
+ hash
+ end
end

MODIFY
mrbgems/mruby-enum-ext/test/enum.rb
mrbgems/mruby-enum-ext/test/enum.rb
@@ -189,7 +189,10 @@ assert("Enumerable#to_h") do
assert_equal({1=>4,3=>8}, c.new.to_h{|k,v|[k,v*2]})
end
-
assert("Enumerable#filter_map") do
assert_equal [4, 8, 12, 16, 20], (1..10).filter_map{|i| i * 2 if i%2==0}
end
+
+assert("Enumerable#tally") do
+ assert_equal({"a"=>1, "b"=>2, "c"=>1}, ["a", "b", "c", "b"].tally)
+end

Implement `Enumerable` tally from Ruby2.7.