Class: Range

Inherits:
Object
  • Object
show all
Defined in:
lib/combinatorics/extensions/range.rb

Instance Method Summary collapse

Instance Method Details

#&(other) ⇒ Range

Finds the intersecting sub-range.

Examples:

(1..100) & (20..200)
# => 20..100

Parameters:

  • other (Range)

    The other range.

Returns:

  • (Range)

    The intersecting sub-range.

Since:

  • 0.2.0



20
21
22
23
24
25
# File 'lib/combinatorics/extensions/range.rb', line 20

def &(other)
  Range.new(
    [self.first, other.first].max,
    [self.last, other.last].min
  )
end

#downto(other) {|subrange| ... } ⇒ Enumerator

Iterates over every sub-range down to the other range.

Examples:

(2..7).downto(1..5).to_a
# => [2..7, 2..6, 2..5, 1..7, 1..6, 1..5]

Parameters:

  • other (Range)

    The lower bounding range.

Yields:

  • (subrange)

    The given block will be passed every sub-range between the two ranges.

Yield Parameters:

  • subrange (Range)

    A sub-range bounded by the beginning of the other range and the ending of the range.

Returns:

  • (Enumerator)

    If no block is given, an enumerator object will be returned.

Since:

  • 0.2.0



85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/combinatorics/extensions/range.rb', line 85

def downto(other)
  return enum_for(:downto,other) unless block_given?

  unless other.kind_of?(Range)
    raise(TypeError,"bad value for range",caller)
  end

  self.first.downto(other.first) do |start|
    self.last.downto(other.last) do |stop|
      yield start..stop
    end
  end
end

#upto(other) {|subrange| ... } ⇒ Enumerator

Iterates over every sub-range up to the other range.

Examples:

(1..5).upto(2..7).to_a
# => [1..5, 1..6, 1..7, 2..5, 2..6, 2..7]

Parameters:

  • other (Range)

    The upper bounding range.

Yields:

  • (subrange)

    The given block will be passed every sub-range between the two ranges.

Yield Parameters:

  • subrange (Range)

    A sub-range bounded by the beginning of the range and the ending of the other range.

Returns:

  • (Enumerator)

    If no block is given, an enumerator object will be returned.

Since:

  • 0.2.0



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/combinatorics/extensions/range.rb', line 49

def upto(other)
  return enum_for(:upto,other) unless block_given?

  unless other.kind_of?(Range)
    raise(TypeError,"bad value for range",caller)
  end

  self.first.upto(other.first) do |start|
    self.last.upto(other.last) do |stop|
      yield start..stop
    end
  end
end