diff options
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 15 | ||||
-rw-r--r-- | activesupport/test/core_ext/enumerable_test.rb | 10 |
2 files changed, 25 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 41ccc62afb..0d7d0159f9 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -30,4 +30,19 @@ module Enumerable #:nodoc: def sum inject(0) { |sum, element| sum + yield(element) } end + + # Convert an enumerable to a hash. Examples: + # + # people.index_by(&:login) + # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...} + # people.index_by { |person| "#{person.first_name} #{person.last_name}" } + # => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...} + # + def index_by + inject({}) do |accum, elem| + accum[yield(elem)] = elem + accum + end + end + end
\ No newline at end of file diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 882111cd79..dada058d56 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -1,4 +1,5 @@ require 'test/unit' +require File.dirname(__FILE__) + '/../../lib/active_support/core_ext/symbol' require File.dirname(__FILE__) + '/../../lib/active_support/core_ext/enumerable' Payment = Struct.new(:price) @@ -24,4 +25,13 @@ class EnumerableTests < Test::Unit::TestCase assert_equal 30, payments.sum(&:price) assert_equal 60, payments.sum { |p| p.price * 2 } end + + def test_index_by + payments = [ Payment.new(5), Payment.new(15), Payment.new(10) ] + assert_equal( + {5 => payments[0], 15 => payments[1], 10 => payments[2]}, + payments.index_by(&:price) + ) + end + end |