Infinite Ranges in Ruby (cont.)
When I wrote yesterday that Ruby ranges may be infinite the first example that came to my mind as I was writing the mail in ruby-talk involved an enumeration of the rationals in [0, 1] and that somewhat obscured my point.
There's a more simple approach where you define <=> and succ in a class which consists of the naturals plus the first infinite ordinals ω, ω + 1, ω + 2, ... In that class 1 .. ω is an infinite range. But I didn't want to present this alternate proof because albeit I could skip set theory jargon altogether, using numbers past infinity was conceptually not a big gain over the previous reasoning.
Late at night I finally was able to construct an analogous argument to the one that uses ordinals, but just using Z × Z, which can be thought as a set of pairs of integers by any programmer and so it was much more understandable in the mailing list. This is the resulting class:
class ZSquared
include Comparable
attr_reader :n, :m
def initialize(n, m)
@n, @m = n, m
end
def succ
self.class.new(n+1, m)
end
def <=>(zs)
[self.m, self.n] <=> [zs.m, zs.n]
end
end
which allows the definition of an infinite Range:
ZSquared.new(0, 0) .. ZSquared.new(0, 1)
So yes, Ruby ranges may be infinite, and thus Range#length defined as a loop over succ wouldn't necessarily terminate.
