在它们之间匹配整数

Match integers among themselves

我有一个问题。我有两个整数范围,例如 100-500 和 600-800。他们是这样的:

范围 1

start_range = 100
end_range = 500

范围 2

start_range_new = 600
end_range_new = 800

我想要一个方法逻辑,我可以在其中匹配两个范围(范围 1 和范围 2),以便这两个范围完全互斥,这意味着这两个范围不相交。

如果两个范围相交,则将局部变量设置为true,如果不相交,则局部变量应为false

variable = !((start_range_new > end_range) || (start_range > end_range_new))
a = (0..20)
b = (15..30)

def exclusive?(x,y)
    return x.first > y.last || x.last < y.first
end

exclusive?(a,b) //False

如果你使用Rails(或ActiveSupport),你可以使用Range#overlaps?方法:

# Compare two ranges and see if they overlap each other

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

如果不想使用ActiveSupport,可以自己实现一个辅助函数:

# Compare two ranges and see if they overlap each other
# overlaps?(1..5, 4..6) # => true
# overlaps?(1..5, 7..9) # => false
def overlaps?(one, another)
  one.cover?(other.first) || other.cover?(one.first)
end