Project

General

Profile

Bug #18983 » bug-20220829-beginless_range.rb

Ruby executable code to demonstrate the point re beginless Range#size. - masasakano (Masa Sakano), 08/29/2022 02:05 PM

 
# Test Ruby script. You can run this.

# class XS taken from the official docs:
# https://ruby-doc.org/core-3.1.2/Range.html#class-Range-label-Ranges+and+User-Defined+Classes
class Xs
include Comparable
attr_accessor :length
def initialize(n)
@length = n
end
def succ
Xs.new(@length + 1)
end
def <=>(other)
@length <=> other.length
end
def to_s
sprintf "%2d #{inspect}", @length
end
def inspect
'X' * @length
end
end

puts "NOTE: Correct (i.e., expected) results."
print "(..3).size should be Infinity: "
p (..3).size # => Float::INFINITY
print "(3..).size should be Infinity: "
p (3..).size # => Float::INFINITY
print "(?a..).size should be nil: "
p (?a..).size # => nil

puts ""
puts "NOTE: unexpected results:"
print "(..?a).size should be nil: "
p (..?a).size # => Float::INFINITY(!)
print "(nil..nil).size should be nil: "
p (nil..nil).size # => Float::INFINITY(!)

puts "NOTE: the following class XS taken from the official docs: https://ruby-doc.org/core-3.1.2/Range.html#class-Range-label-Ranges+and+User-Defined+Classes"
print "(Xs.new(5)..).size should be nil: "
p (Xs.new(5)..).size # => nil
print "(..Xs.new(5)).size should be nil: "
p (..Xs.new(5)).size # => Float::INFINITY(!)


(1-1/2)