summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-enum-ext
diff options
context:
space:
mode:
Diffstat (limited to 'mrbgems/mruby-enum-ext')
-rw-r--r--mrbgems/mruby-enum-ext/mrblib/enum.rb30
-rw-r--r--mrbgems/mruby-enum-ext/test/enum.rb8
2 files changed, 38 insertions, 0 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb
index b427bd67e..178496e7e 100644
--- a/mrbgems/mruby-enum-ext/mrblib/enum.rb
+++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb
@@ -826,4 +826,34 @@ module Enumerable
end
hash.values
end
+
+ def filter_map(&blk)
+ return to_enum(:find_index, val) 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 6929d8ddc..f0301a2d9 100644
--- a/mrbgems/mruby-enum-ext/test/enum.rb
+++ b/mrbgems/mruby-enum-ext/test/enum.rb
@@ -188,3 +188,11 @@ assert("Enumerable#to_h") do
assert_equal h0, 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