aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/enumerable.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport/lib/active_support/core_ext/enumerable.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb17
1 files changed, 14 insertions, 3 deletions
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index 47ff19e963..8e148cc1b4 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -1,3 +1,5 @@
+require 'active_support/ordered_hash'
+
module Enumerable
# Ruby 1.8.7 introduces group_by, but the result isn't ordered. Override it.
remove_method(:group_by) if [].respond_to?(:group_by) && RUBY_VERSION < '1.9'
@@ -18,10 +20,19 @@ module Enumerable
# "2006-02-24 -> Transcript, Transcript"
# "2006-02-23 -> Transcript"
def group_by
- inject ActiveSupport::OrderedHash.new do |grouped, element|
- (grouped[yield(element)] ||= []) << element
- grouped
+ assoc = ActiveSupport::OrderedHash.new
+
+ each do |element|
+ key = yield(element)
+
+ if assoc.has_key?(key)
+ assoc[key] << element
+ else
+ assoc[key] = [element]
+ end
end
+
+ assoc
end unless [].respond_to?(:group_by)
# Calculates a sum from the elements. Examples: