summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-enum-ext
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2019-09-16 08:06:22 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2019-09-16 10:10:09 +0900
commita57b6f8ed06b96747d9521b3212a7959f7371a15 (patch)
treec5e48652193c8d9c1d5ae1ac0b7ec2993293129c /mrbgems/mruby-enum-ext
parentd380c7d26f1056c021281d56c2d7110f9d5ce2d1 (diff)
downloadmruby-a57b6f8ed06b96747d9521b3212a7959f7371a15.tar.gz
mruby-a57b6f8ed06b96747d9521b3212a7959f7371a15.zip
Implement `Enumerable` tally from Ruby2.7.
Diffstat (limited to 'mrbgems/mruby-enum-ext')
-rw-r--r--mrbgems/mruby-enum-ext/mrblib/enum.rb17
-rw-r--r--mrbgems/mruby-enum-ext/test/enum.rb5
2 files changed, 21 insertions, 1 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb
index e354a4c5e..178496e7e 100644
--- a/mrbgems/mruby-enum-ext/mrblib/enum.rb
+++ b/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
diff --git a/mrbgems/mruby-enum-ext/test/enum.rb b/mrbgems/mruby-enum-ext/test/enum.rb
index 8c8daa678..f0301a2d9 100644
--- a/mrbgems/mruby-enum-ext/test/enum.rb
+++ b/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