diff options
| author | Hiroshi Mimaki <[email protected]> | 2019-10-18 14:46:03 +0900 |
|---|---|---|
| committer | Hiroshi Mimaki <[email protected]> | 2019-10-18 14:46:03 +0900 |
| commit | b6546835457d1935a9c77965686b2a1256874d96 (patch) | |
| tree | 724cfd71a7c956b0648e8c58f3717d797fff5f29 /mrbgems/mruby-enum-ext | |
| parent | 8ee516436b8d174a50764939bee23a442aa00b3f (diff) | |
| parent | 20d01f118ddb7e7f2f36926a7a3db35573611857 (diff) | |
| download | mruby-b6546835457d1935a9c77965686b2a1256874d96.tar.gz mruby-b6546835457d1935a9c77965686b2a1256874d96.zip | |
Merge master.
Diffstat (limited to 'mrbgems/mruby-enum-ext')
| -rw-r--r-- | mrbgems/mruby-enum-ext/mrblib/enum.rb | 34 | ||||
| -rw-r--r-- | mrbgems/mruby-enum-ext/test/enum.rb | 11 |
2 files changed, 38 insertions, 7 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb index 99b9cddba..f15511925 100644 --- a/mrbgems/mruby-enum-ext/mrblib/enum.rb +++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb @@ -811,10 +811,6 @@ module Enumerable h end - def nil.to_h - {} - end - def uniq(&block) hash = {} if block @@ -830,4 +826,34 @@ module Enumerable end hash.values end + + def filter_map(&blk) + return to_enum(:filter_map) unless blk + + ary = [] + self.each do |x| + x = blk.call(x) + ary.push x if x + end + ary + 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 64b1bbda9..f0301a2d9 100644 --- a/mrbgems/mruby-enum-ext/test/enum.rb +++ b/mrbgems/mruby-enum-ext/test/enum.rb @@ -186,8 +186,13 @@ assert("Enumerable#to_h") do h = c.new.to_h assert_equal Hash, h.class assert_equal h0, h - # mruby-enum-ext also provides nil.to_h - assert_equal Hash.new, nil.to_h - 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 |
