diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2019-09-16 08:06:22 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2019-09-16 10:10:09 +0900 |
| commit | a57b6f8ed06b96747d9521b3212a7959f7371a15 (patch) | |
| tree | c5e48652193c8d9c1d5ae1ac0b7ec2993293129c /mrbgems/mruby-enum-ext/mrblib/enum.rb | |
| parent | d380c7d26f1056c021281d56c2d7110f9d5ce2d1 (diff) | |
| download | mruby-a57b6f8ed06b96747d9521b3212a7959f7371a15.tar.gz mruby-a57b6f8ed06b96747d9521b3212a7959f7371a15.zip | |
Implement `Enumerable` tally from Ruby2.7.
Diffstat (limited to 'mrbgems/mruby-enum-ext/mrblib/enum.rb')
| -rw-r--r-- | mrbgems/mruby-enum-ext/mrblib/enum.rb | 17 |
1 files changed, 17 insertions, 0 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 |
