Skip to content
Browse files

Fix up Enumerable#group_by

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8604 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 7e56c72 commit e9b862acb02f9b6a507023e493a9abb2a2fb62da @jeremy jeremy committed Jan 9, 2008
View
21 activesupport/lib/active_support/core_ext/enumerable.rb
@@ -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
View
8 activesupport/test/core_ext/enumerable_test.rb
@@ -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

0 comments on commit e9b862a

Please sign in to comment.
Something went wrong with that request. Please try again.