aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/enumerable.rb
diff options
context:
space:
mode:
authorJeremy Kemper <jeremy@bitsweat.net>2008-01-09 08:37:36 +0000
committerJeremy Kemper <jeremy@bitsweat.net>2008-01-09 08:37:36 +0000
commite9b862acb02f9b6a507023e493a9abb2a2fb62da (patch)
tree99b2e6a488bff56f540136f03ede39bbe043c67a /activesupport/lib/active_support/core_ext/enumerable.rb
parent7e56c72fae45f26b1ec2acbd20d404b189852a77 (diff)
downloadrails-e9b862acb02f9b6a507023e493a9abb2a2fb62da.tar.gz
rails-e9b862acb02f9b6a507023e493a9abb2a2fb62da.tar.bz2
rails-e9b862acb02f9b6a507023e493a9abb2a2fb62da.zip
Fix up Enumerable#group_by
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8604 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activesupport/lib/active_support/core_ext/enumerable.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb21
1 files changed, 14 insertions, 7 deletions
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index c3a351538f..35a8e0538c 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/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 @@ module Enumerable
accum
end
end
-
end