Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 8605

Show
Ignore:
Timestamp:
01/09/08 08:40:07 (1 year ago)
Author:
bitsweat
Message:

Merge [8604] to stable: fix up Enumerable#group_by

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • branches/2-0-stable/activesupport/lib/active_support/core_ext/enumerable.rb

    r8585 r8605  
    1616  #   "2006-02-23 -> Transcript" 
    1717  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 
    2225      else 
    23         groups << [value, [element]] 
     26        group = [element] 
     27        groups << [index, group] 
     28        grouped[index] = group 
    2429      end 
    25       groups 
     30 
     31      grouped 
    2632    end 
     33 
     34    groups 
    2735  end if RUBY_VERSION < '1.9' 
    2836 
     
    6573    end 
    6674  end 
    67    
    6875end 
  • branches/2-0-stable/activesupport/test/core_ext/enumerable_test.rb

    r8363 r8605  
    1616    end 
    1717 
    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 } 
    2022    end 
     23 
     24    assert_equal objects.uniq.map(&:name), grouped.map { |name, group| name } 
    2125  end 
    2226