Sha256: 6a13e36e675251a2a84457dc518fcc71fd8be05ee6d59639d3850111d2a04432

Contents?: true

Size: 944 Bytes

Versions: 8

Compression:

Stored size: 944 Bytes

Contents

module Enumerable

  # Returns all items that are equal in terms of the supplied block.
  # If no block is given objects are considered to be equal if they
  # return the same value for Object#hash and if obj1 == obj2.
  #
  #   [1, 2, 2, 3, 4, 4].commonality # => { 2 => [2], 4 => [4] }
  #
  #   ["foo", "bar", "a"].commonality { |str| str.length }
  #   # => { 3 => ["foo, "bar"] }
  #
  #   # Returns all persons that share their last name with another person.
  #   persons.collisions { |person| person.last_name }
  #
  # CREDIT: Florian Gross

  def commonality( &block )
    had_no_block = !block
    block ||= lambda { |item| item }
    result = Hash.new { |hash, key| hash[key] = Array.new }
    self.each do |item|
      key = block.call(item)
      result[key] << item
    end
    result.reject! do |key, values|
      values.size <= 1
    end
    #return had_no_block ? result.values.flatten : result
    return result
  end

end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
facets-2.8.2 lib/core/facets/enumerable/commonality.rb
facets-2.8.1 lib/core/facets/enumerable/commonality.rb
facets-2.8.0 lib/core/facets/enumerable/commonality.rb
facets-2.7.0 lib/core/facets/enumerable/commonality.rb
facets-2.6.0 lib/core/facets/enumerable/commonality.rb
facets-2.5.0 lib/core/facets/enumerable/commonality.rb
facets-2.5.1 lib/core/facets/enumerable/commonality.rb
facets-2.5.2 lib/core/facets/enumerable/commonality.rb