Sha256: b324ed42bb3eeec10ec1a757bb46b0f069b85aa2407e7fa879ffe3e5a758078f

Contents?: true

Size: 1.03 KB

Versions: 20

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

class Range
  # Compare two ranges and see if they overlap each other
  #  (1..5).overlap?(4..6) # => true
  #  (1..5).overlap?(7..9) # => false
  unless Range.method_defined?(:overlap?) # Ruby 3.3+
    def overlap?(other)
      raise TypeError unless other.is_a? Range

      self_begin = self.begin
      other_end = other.end
      other_excl = other.exclude_end?

      return false if _empty_range?(self_begin, other_end, other_excl)

      other_begin = other.begin
      self_end = self.end
      self_excl = self.exclude_end?

      return false if _empty_range?(other_begin, self_end, self_excl)
      return true if self_begin == other_begin

      return false if _empty_range?(self_begin, self_end, self_excl)
      return false if _empty_range?(other_begin, other_end, other_excl)

      true
    end

    private
    def _empty_range?(b, e, excl)
      return false if b.nil? || e.nil?

      comp = b <=> e
      comp.nil? || comp > 0 || (comp == 0 && excl)
    end
  end

  alias :overlaps? :overlap?
end

Version data entries

20 entries across 20 versions & 2 rubygems

Version Path
activesupport-8.0.0 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.2 lib/active_support/core_ext/range/overlap.rb
activesupport-8.0.0.rc2 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.1.2 lib/active_support/core_ext/range/overlap.rb
activesupport-8.0.0.rc1 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.1.1 lib/active_support/core_ext/range/overlap.rb
activesupport-8.0.0.beta1 lib/active_support/core_ext/range/overlap.rb
omg-activesupport-8.0.0.alpha9 lib/active_support/core_ext/range/overlap.rb
omg-activesupport-8.0.0.alpha8 lib/active_support/core_ext/range/overlap.rb
omg-activesupport-8.0.0.alpha7 lib/active_support/core_ext/range/overlap.rb
omg-activesupport-8.0.0.alpha4 lib/active_support/core_ext/range/overlap.rb
omg-activesupport-8.0.0.alpha3 lib/active_support/core_ext/range/overlap.rb
omg-activesupport-8.0.0.alpha2 lib/active_support/core_ext/range/overlap.rb
omg-activesupport-8.0.0.alpha1 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.1 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.0 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.0.rc1 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.0.beta3 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.0.beta2 lib/active_support/core_ext/range/overlap.rb
activesupport-7.2.0.beta1 lib/active_support/core_ext/range/overlap.rb