Search code examples
ruby

Check if two ranges overlap in ruby


I know that I can do:

(1..30).cover?(2)
=> true

But when I try to do the same with another range it always returns false:

(1..30).cover?(2..3)
=> false

So my question is - is there any elegant way to compare two ranges in ruby? In my case I want to check if two DateTime-ranges overlap. Thanks in advance.


Solution

  • There is Range#overlap? In Ruby 3.3+

    It returns true if ranges overlap each other, otherwise false

    It works with different kinds of ranges:

    (5..10).overlap?(10..20)
    # => true
    
    ('a'..'e').overlap?('b'..'f')
    # => true
    

    It returns false when begin > end:

    (5..1).overlap?(2..3)
    # => false
    

    It returns false when try to check incomparable kinds of ranges:

    (5..10).overlap?('a'..'e') 
    # => false
    

    It works with exclusive ranges:

    (5..10).overlap?(1...5)
    # => false
    
    (1...5).overlap?(5..10)
    # => false
    

    It works with endless and beginless ranges:

    (1..).overlap?(..1)
    # => true
    
    (1..).overlap?(...1)
    # => false
    

    It raises error when try to pass not range

    (1..5).overlap?(1)
    # raise TypeError (expected Range)