diff options
Diffstat (limited to 'activesupport/lib/active_support')
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 15 |
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 |