From a57b6f8ed06b96747d9521b3212a7959f7371a15 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Mon, 16 Sep 2019 08:06:22 +0900 Subject: Implement `Enumerable` tally from Ruby2.7. --- mrbgems/mruby-enum-ext/mrblib/enum.rb | 17 +++++++++++++++++ mrbgems/mruby-enum-ext/test/enum.rb | 5 ++++- 2 files changed, 21 insertions(+), 1 deletion(-) 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 -- cgit v1.2.3