Sha256: 7ddd5ac25a4129f6fc44ca92f58f7700d55c8a9492e462934bf042f4763fadea

Contents?: true

Size: 1.12 KB

Versions: 22

Compression:

Stored size: 1.12 KB

Contents

require 'facet/enumerable/each_combination'

class Array

  # Processes each unique pair (of indices, not value) 
  # in the array by yielding them to the supplied block.
  #
  #   a = [1,2,3,4]
  #   a.each_unique_pair{ |a,b| puts a+','+b }
  #
  # produces
  #
  #   1,2
  #   1,3
  #   1,4
  #   2,3
  #   2,4
  #   3,4
  #
  # This does not guarantee the uniqueness of values. 
  # For example:
  #
  #   a = [1,2,1]
  #   a.each_unique_pair{ |a,b| puts a+','+b }
  #
  # prduces
  #
  #   1,2
  #   1,1
  #   2,1
  #
  # This is equivalent to <tt>each_combination(2){ ... }</tt>.
  def each_unique_pair(&yld)
    self.each_combination(2,&yld)
    #s = self.to_a
    #self.each_with_index{ |a,i|
    #  self[(i+1)..-1].each{ |b| yield a,b }
    #}
  end

end



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

  require 'test/unit'

  class TCEnumerable < Test::Unit::TestCase

    def test_each_unique_pair
      r = []
      a = [1,2,3,4]
      a.each_unique_pair{ |a,b| r << [a,b] }
      assert_equal( [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]], r )
    end

  end

=end

Version data entries

22 entries across 22 versions & 1 rubygems

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