Sha256: e934887551e83f6441d0a9e0ddff405ab050acf7d23c81d94cc1b91c1997757a

Contents?: true

Size: 821 Bytes

Versions: 2

Compression:

Stored size: 821 Bytes

Contents

module Enumerable #:nodoc:
  def first_match
    match = nil
    each do |items|
      break if match = yield(items)
    end
    match
  end

  # Collect an enumerable into sets, grouped by the result of a block. Useful,
  # for example, for grouping records by date.
  #
  # e.g. 
  #
  #   latest_transcripts.group_by(&:day).each do |day, transcripts| 
  #     p "#{day} -> #{transcripts.map(&:class) * ', '}"
  #   end
  #   "2006-03-01 -> Transcript"
  #   "2006-02-28 -> Transcript"
  #   "2006-02-27 -> Transcript, Transcript"
  #   "2006-02-26 -> Transcript, Transcript"
  #   "2006-02-25 -> Transcript"
  #   "2006-02-24 -> Transcript, Transcript"
  #   "2006-02-23 -> Transcript"
  def group_by
    inject({}) do |groups, element|
      (groups[yield(element)] ||= []) << element
      groups
    end
  end 
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
activesupport-1.3.1 lib/active_support/core_ext/enumerable.rb
activesupport-1.3.0 lib/active_support/core_ext/enumerable.rb