跳至内容 跳至搜索
方法
#
O
S

实例公共方法

_empty_range?(b, e, excl)

# File activesupport/lib/active_support/core_ext/range/overlap.rb, line 31
def _empty_range?(b, e, excl)
  return false if b.nil? || e.nil?

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

overlap?(other)

比较两个范围,查看它们是否重叠

(1..5).overlap?(4..6) # => true
(1..5).overlap?(7..9) # => false
也别名为: overlaps?
# File activesupport/lib/active_support/core_ext/range/overlap.rb, line 8
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

overlaps?(other)

别名: overlap?

sole()

返回范围内的唯一项。如果不存在项,或存在多个项,则引发 Enumerable::SoleItemExpectedError

(1..1).sole   # => 1
(2..1).sole   # => Enumerable::SoleItemExpectedError: no item found
(..1).sole    # => Enumerable::SoleItemExpectedError: infinite range cannot represent a sole item
# File activesupport/lib/active_support/core_ext/range/sole.rb, line 10
def sole
  if self.begin.nil? || self.end.nil?
    raise ActiveSupport::EnumerableCoreExt::SoleItemExpectedError, "infinite range '#{inspect}' cannot represent a sole item"
  end

  super
end