aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib
diff options
context:
space:
mode:
authorNicholas Seckar <nseckar@gmail.com>2006-06-24 16:42:48 +0000
committerNicholas Seckar <nseckar@gmail.com>2006-06-24 16:42:48 +0000
commita55265132b37c6fb8ac15a96b44e64a64bcd4c45 (patch)
tree28cec2311c882ca64566edae6484950b664d03ad /activesupport/lib
parent84d9a292fecc922d4e2cf7b3992e91a182f28b46 (diff)
downloadrails-a55265132b37c6fb8ac15a96b44e64a64bcd4c45.tar.gz
rails-a55265132b37c6fb8ac15a96b44e64a64bcd4c45.tar.bz2
rails-a55265132b37c6fb8ac15a96b44e64a64bcd4c45.zip
Add Enumerable#index_by
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4491 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activesupport/lib')
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb15
1 files changed, 15 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