diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2008-01-09 08:37:36 +0000 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2008-01-09 08:37:36 +0000 |
commit | e9b862acb02f9b6a507023e493a9abb2a2fb62da (patch) | |
tree | 99b2e6a488bff56f540136f03ede39bbe043c67a /activesupport | |
parent | 7e56c72fae45f26b1ec2acbd20d404b189852a77 (diff) | |
download | rails-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')
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 21 | ||||
-rw-r--r-- | activesupport/test/core_ext/enumerable_test.rb | 8 |
2 files changed, 20 insertions, 9 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 diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 97e3ff6377..234dc98de8 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -15,9 +15,13 @@ class EnumerableTests < Test::Unit::TestCase 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 |