add Enumerable#group_by

This commit is contained in:
skandhas
2013-03-22 16:07:10 +08:00
parent 39a553d44e
commit 35bcc8f850
2 changed files with 26 additions and 0 deletions
+19
View File
@@ -142,4 +142,23 @@ module Enumerable
block.call(ary) unless ary.empty?
end
##
# call-seq:
# enum.group_by {| obj | block } -> a_hash
#
# Returns a hash, which keys are evaluated result from the
# block, and values are arrays of elements in <i>enum</i>
# corresponding to the key.
#
# (1..6).group_by {|i| i%3} #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
def group_by(&block)
h = {}
self.each do |e|
key = block.call(e)
h.key?(key) ? (h[key] << e) : (h[key] = [e])
end
h
end
end
+7
View File
@@ -35,3 +35,10 @@ assert("Enumerable#each_slice") do
assert_equal a, [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
end
assert("Enumerable#group_by") do
r = (1..6).group_by {|i| i % 3 }
assert_equal r[0], [3, 6]
assert_equal r[1], [1, 4]
assert_equal r[2], [2, 5]
end