From a55265132b37c6fb8ac15a96b44e64a64bcd4c45 Mon Sep 17 00:00:00 2001 From: Nicholas Seckar Date: Sat, 24 Jun 2006 16:42:48 +0000 Subject: Add Enumerable#index_by git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4491 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activesupport/lib/active_support/core_ext/enumerable.rb | 15 +++++++++++++++ activesupport/test/core_ext/enumerable_test.rb | 10 ++++++++++ 2 files changed, 25 insertions(+) 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" => , "chade-" => , ...} + # people.index_by { |person| "#{person.first_name} #{person.last_name}" } + # => { "Chade- Fowlersburg-e" => , "David Heinemeier Hansson" => , ...} + # + 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 -- cgit v1.2.3