Skip to content
This repository
Browse code

Fix up Enumerable#group_by

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8604 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
commit e9b862acb02f9b6a507023e493a9abb2a2fb62da 1 parent 7e56c72
Jeremy Kemper jeremy authored
21 activesupport/lib/active_support/core_ext/enumerable.rb
@@ -15,15 +15,23 @@ module Enumerable
15 15 # "2006-02-24 -> Transcript, Transcript"
16 16 # "2006-02-23 -> Transcript"
17 17 def group_by
18   - inject([]) do |groups, element|
19   - value = yield(element)
20   - if (last_group = groups.last) && last_group.first == value
21   - last_group.last << element
  18 + groups = []
  19 +
  20 + inject({}) do |grouped, element|
  21 + index = yield(element)
  22 +
  23 + if group = grouped[index]
  24 + group << element
22 25 else
23   - groups << [value, [element]]
  26 + group = [element]
  27 + groups << [index, group]
  28 + grouped[index] = group
24 29 end
25   - groups
  30 +
  31 + grouped
26 32 end
  33 +
  34 + groups
27 35 end if RUBY_VERSION < '1.9'
28 36
29 37 # Calculates a sum from the elements. Examples:
@@ -64,5 +72,4 @@ def index_by
64 72 accum
65 73 end
66 74 end
67   -
68 75 end
8 activesupport/test/core_ext/enumerable_test.rb
@@ -15,9 +15,13 @@ def test_group_by
15 15 people << p
16 16 end
17 17
18   - objects.group_by {|object| object.name}.each do |name, group|
19   - assert group.all? {|person| person.name == name}
  18 + grouped = objects.group_by { |object| object.name }
  19 +
  20 + grouped.each do |name, group|
  21 + assert group.all? { |person| person.name == name }
20 22 end
  23 +
  24 + assert_equal objects.uniq.map(&:name), grouped.map { |name, group| name }
21 25 end
22 26
23 27 def test_sums

0 comments on commit e9b862a

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