Add Enumerable#index_by

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4491 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
Nicholas Seckar
2006-06-24 16:42:48 +00:00
parent 84d9a292fe
commit a55265132b
2 changed files with 25 additions and 0 deletions

View File

@@ -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

View File

@@ -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