Skip to content

Instantly share code, notes, and snippets.

@yaauie
Created May 23, 2013 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaauie/5639462 to your computer and use it in GitHub Desktop.
Save yaauie/5639462 to your computer and use it in GitHub Desktop.

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