Sha256: 9fca9671ca01e9e889ae9966eef994f4b7df97b0caed122c281c6f0e822fc09d

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

require 'nano/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

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.9.0 lib/nano/enumerable/each_unique_pair.rb