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

Changeset 4491

Show
Ignore:
Timestamp:
06/24/06 16:42:48 (3 years ago)
Author:
ulysses
Message:

Add Enumerable#index_by

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activesupport/lib/active_support/core_ext/enumerable.rb

    r4490 r4491  
    3131    inject(0) { |sum, element| sum + yield(element) } 
    3232  end 
     33   
     34  # Convert an enumerable to a hash. Examples: 
     35  #  
     36  #   people.index_by(&:login) 
     37  #     => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...} 
     38  #   people.index_by { |person| "#{person.first_name} #{person.last_name}" } 
     39  #     => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...} 
     40  #  
     41  def index_by 
     42    inject({}) do |accum, elem| 
     43      accum[yield(elem)] = elem 
     44      accum 
     45    end 
     46  end 
     47   
    3348end 
  • trunk/activesupport/test/core_ext/enumerable_test.rb

    r4489 r4491  
    11require 'test/unit' 
     2require File.dirname(__FILE__) + '/../../lib/active_support/core_ext/symbol' 
    23require File.dirname(__FILE__) + '/../../lib/active_support/core_ext/enumerable' 
    34 
     
    2526    assert_equal 60, payments.sum { |p| p.price * 2 } 
    2627  end 
     28   
     29  def test_index_by 
     30    payments = [ Payment.new(5), Payment.new(15), Payment.new(10) ] 
     31    assert_equal( 
     32      {5 => payments[0], 15 => payments[1], 10 => payments[2]}, 
     33      payments.index_by(&:price) 
     34    ) 
     35  end 
     36   
    2737end