Sha256: 93cca94be8646f17c012f8622f7e0b6c682657b8df42ee6ea23dd3a5344f40e6

Contents?: true

Size: 1.28 KB

Versions: 6

Compression:

Stored size: 1.28 KB

Contents

#--
# CREDIT Gavin Sinclair
# CREDIT Gregory of Laurel, Maryland
#++

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.

  def partition_by #:yield:
    r = Hash.new{ |h,k| h[k]=[] }
    each do |e|
      r[ yield(e) ] << e
    end
    return r
  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

6 entries across 6 versions & 1 rubygems

Version Path
facets-1.8.49 lib/facets/core/enumerable/partition_by.rb
facets-1.8.0 lib/facets/core/enumerable/partition_by.rb
facets-1.8.20 lib/facets/core/enumerable/partition_by.rb
facets-1.8.51 lib/facets/core/enumerable/partition_by.rb
facets-1.8.54 lib/facets/core/enumerable/partition_by.rb
facets-1.8.8 lib/facets/core/enumerable/partition_by.rb