(Ruby) How do you check whether a range contains a subset of another range?

后端 未结 10 1485
轻奢々
轻奢々 2021-02-05 11:06

If I have two ranges that overlap:

x = 1..10
y = 5..15

When I say:

puts x.include? y 

the output is:

相关标签:
10条回答
  • 2021-02-05 11:34

    Some helpful enumerable methods:

    # x is a 'subset' of y
    x.all?{|n| y.include? n}
    # x and y overlap
    x.any?{|n| y.include? n}
    # x and y do not overlap
    x.none?{|n| y.include? n}
    # x and y overlap one time
    x.one?{|n| y.include? n}
    
    0 讨论(0)
  • 2021-02-05 11:40

    But if I want it to be "true" when there is partial overlap between two ranges, how would I write that?

    You can convert the ranges to an array, and use the & operator (conjunction). This returns a new array with all the elements occuring in both arrays. If the resulting array is not empty, that means, that there are some overlapping elements:

    def overlap?(range_1, range_2)
      !(range_1.to_a & range_2.to_a).empty?
    end
    
    0 讨论(0)
  • 2021-02-05 11:40

    Rails has Range#overlaps?

    def overlaps?(other)
      cover?(other.first) || other.cover?(first)
    end
    
    0 讨论(0)
  • 2021-02-05 11:42

    Be careful using this with large ranges but this is an elegant way to do it:

    (x.to_a & y.to_a).empty?
    
    0 讨论(0)
提交回复
热议问题