Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

RFC: Range#empty?

Often times it is useful to know whether a Range is empty without iterating over it or converting it to an array, especially with large (read: potentially infinite) ranges. This RFC is an attempt to find an efficient, always-correct, simple implementation of Range#empty?.

Current Best Implementation

module Range::IsEmpty
  def empty?
    if self.exclude_end?
      self.end <= self.begin
    else
      self.end < self.begin
    end
  end
end

Range.instance_exec { include Range::IsEmpty }

Rejected Implementations:

Avoid to_a (infinite ranges exist)

def empty?
  to_a.empty?
end

Raises exception for (-Float::INFINITY) .. (Float::INFINITY)

def empty?
  first(1).empty?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment