Sha256: 0ba7e7712f934626f5f94a8c127d40093988e0b43192844d7d3e6f9f48d1b0e9

Contents?: true

Size: 1.27 KB

Versions: 20

Compression:

Stored size: 1.27 KB

Contents

module Enumerable

  # See Enumerable#partition for the background. #partition_by is best
  # explained by example.
  #
  #   (1..5).partition_by { |n| n % 3 }
  #        #=> { 0 => [3], 1 => [1, 4], 2 => [2,5] } 
  #
  #   ["I had", 1, "dollar and", 50, "cents"].partition_by { |e| e.class }
  #        #=> { String => ["I had","dollar and","cents"], Fixnum => [1,50] } 
  #
  # #partition_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.
  #--
  # Credit goes to Gavin Sinclair.
  #++
  def partition_by #:yield:
    result = {}
    self.each do |e|
      value = yield e
      (result[value] ||= []) << e
    end
    result
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCEnumerable < Test::Unit::TestCase

    def test_partition_by
      x = (1..5).partition_by{ |n| n % 3 }
      o = { 0 => [3], 1 => [1, 4], 2 => [2,5] }
      assert_equal( o, x )
      x = ["I had", 1, "dollar and", 50, "cents"].partition_by { |e| e.class }
      o = { String => ["I had","dollar and","cents"], Fixnum => [1,50] }
      assert_equal( o, x )
    end

  end

=end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
facets-1.0.3 packages/core/lib/facet/enumerable/partition_by.rb
facets-0.9.0 lib/nano/enumerable/partition_by.rb
facets-1.0.0 lib/facet/enumerable/partition_by.rb
facets-1.1.0 lib/facet/enumerable/partition_by.rb
facets-1.2.0 lib/facets/core/enumerable/partition_by.rb
facets-1.2.1 lib/facets/core/enumerable/partition_by.rb
facets-1.3.0 lib/facets/core/enumerable/partition_by.rb
facets-1.3.1 lib/facets/core/enumerable/partition_by.rb
facets-1.3.2 lib/facets/core/enumerable/partition_by.rb
facets-1.3.3 lib/facets/core/enumerable/partition_by.rb
facets-1.4.0 lib/facets/core/enumerable/partition_by.rb
facets-1.4.1 lib/facets/core/enumerable/partition_by.rb
facets-1.4.2 lib/facets/core/enumerable/partition_by.rb
facets-1.4.3 lib/facets/core/enumerable/partition_by.rb
facets-1.4.4 lib/facets/core/enumerable/partition_by.rb
facets-1.4.5 lib/facets/core/enumerable/partition_by.rb
facets-1.7.0 lib/facets/core/enumerable/partition_by.rb
facets-1.7.30 lib/facets/core/enumerable/partition_by.rb
facets-1.7.38 lib/facets/core/enumerable/partition_by.rb
facets-1.7.46 lib/facets/core/enumerable/partition_by.rb