提交 e9b862ac 编写于 作者: J Jeremy Kemper

Fix up Enumerable#group_by


git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8604 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
上级 7e56c72f
......@@ -15,15 +15,23 @@ module Enumerable
# "2006-02-24 -> Transcript, Transcript"
# "2006-02-23 -> Transcript"
def group_by
inject([]) do |groups, element|
value = yield(element)
if (last_group = groups.last) && last_group.first == value
last_group.last << element
groups = []
inject({}) do |grouped, element|
index = yield(element)
if group = grouped[index]
group << element
else
groups << [value, [element]]
group = [element]
groups << [index, group]
grouped[index] = group
end
groups
grouped
end
groups
end if RUBY_VERSION < '1.9'
# Calculates a sum from the elements. Examples:
......@@ -64,5 +72,4 @@ def index_by
accum
end
end
end
......@@ -15,9 +15,13 @@ def test_group_by
people << p
end
objects.group_by {|object| object.name}.each do |name, group|
assert group.all? {|person| person.name == name}
grouped = objects.group_by { |object| object.name }
grouped.each do |name, group|
assert group.all? { |person| person.name == name }
end
assert_equal objects.uniq.map(&:name), grouped.map { |name, group| name }
end
def test_sums
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册