Module: CoreExtensions::Range::Checks

Included in:
Operations
Defined in:
lib/core_extensions/range/checks.rb

Instance Method Summary collapse

Instance Method Details

#beginless?Boolean

Returns ‘true` if `self` is beginless, `false` otherwise.

Returns:

  • (Boolean)


38
39
40
# File 'lib/core_extensions/range/checks.rb', line 38

def beginless?
  self.begin.nil?
end

#endless?Boolean

Returns ‘true` if `self` is endless, `false` otherwise.

Returns:

  • (Boolean)


33
34
35
# File 'lib/core_extensions/range/checks.rb', line 33

def endless?
  self.end.nil?
end

#overlaps?(other) ⇒ Boolean

Checks whether or not ‘other` overlaps with `self`.

Examples:

Overlapping range

(1..4).overlaps?(2..6) #=> true

Non-overlapping range

(1..4).overlaps?(5..7) #=> false

Parameters:

  • other (Range)

    The range to check for overlap with ‘self`.

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/core_extensions/range/checks.rb', line 17

def overlaps?(other)
  return true if self == other

  if endless? || other.endless?
    endless_range_overlaps?(other)
  elsif self.end == other.begin || other.end == self.begin
    # If `a.end` is the same as `b.begin`, but `a.exclude_end?` is true,
    # then the ranges do not overlap. Similar in the other direction.
    (self.end == other.begin && !exclude_end?) ||
      (other.end == self.begin && !other.exclude_end?)
  else
    self.begin <= other.end && other.begin <= self.end
  end
end