Sha256: 62bd58fb0fdac5b2ab2f160af58c289ce87663199ffedafffa3aba3f8a82c31b

Contents?: true

Size: 837 Bytes

Versions: 7

Compression:

Stored size: 837 Bytes

Contents

module Enumerable

  unless method_defined?(:group_by) # 1.9

    # Enumerable#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] }
    #
    # Applied to an array.
    #
    #   ["I had", 1, "dollar and", 50, "cents"].group_by { |e| e.class }
    #   #=> { String => ["I had","dollar and","cents"], Fixnum => [1,50] }
    #
    # Applied to a hash:
    #
    #   {:a=>1, :b=>2, :c=>1}.group_by{ |k,v| v }
    #   #=> { 1=>[[:c,1], [:a,1]], 2=>[[:b,2]] }
    #
    # CREDIT: Erik Veenstra

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

  end

end

Version data entries

7 entries across 6 versions & 1 rubygems

Version Path
facets-2.9.3 lib/core/facets/enumerable/group_by.rb
facets-2.9.2 lib/core/facets/enumerable/group_by.rb
facets-2.9.2 src/core/facets/enumerable/group_by.rb
facets-2.9.1 lib/core/facets/enumerable/group_by.rb
facets-2.9.0 lib/core/facets/enumerable/group_by.rb
facets-2.9.0.pre.2 lib/core/facets/enumerable/group_by.rb
facets-2.9.0.pre.1 lib/core/facets/enumerable/group_by.rb