Sha256: 88a68877d8b624b170a8dd16868e888a202695892d681a50bb3b4743e28a40e6

Contents?: true

Size: 738 Bytes

Versions: 6

Compression:

Stored size: 738 Bytes

Contents

module Enumerable

  unless method_defined?(:group_by) or defined?(::ActiveSupport)  # 1.9 or ActiveSupport

    # #group_by is used to group items in a collection by something they
    # have in common.  The common factor is the key in the resulting hash, the
    # array of like elements is the value.
    #
    #   (1..5).group_by { |n| n % 3 }
    #        #=> { 0 => [3], 1 => [1, 4], 2 => [2,5] }
    #
    #   ["I had", 1, "dollar and", 50, "cents"].group_by { |e| e.class }
    #        #=> { String => ["I had","dollar and","cents"], Fixnum => [1,50] }
    #
    # CREDIT: Erik Veenstra

    def group_by #:yield:
      #h = k = e = nil
      r = Hash.new
      each{ |e| (r[yield(e)] ||= []) << e }
      r
    end

  end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
facets-2.8.4 lib/core/facets/enumerable/group_by.rb
facets-2.8.3 lib/core/facets/enumerable/group_by.rb
facets-2.8.2 lib/core/facets/enumerable/group_by.rb
facets-2.8.1 lib/core/facets/enumerable/group_by.rb
facets-2.8.0 lib/core/facets/enumerable/group_by.rb
facets-2.7.0 lib/core/facets/enumerable/group_by.rb