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

后端 未结 10 1473
轻奢々
轻奢々 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:27

    You could also convert the ranges to sets, since you're basically doing set intersection here. Might be easier if you are dealing with more than two ranges.

    x = (1..10).to_set
    y = (5..15).to_set
    !(x & y).empty? #returns true (true == overlap, false == no overlap)
    

提交回复
热议问题