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