Feature #20483
openMore intuitive initialisation of null Range
Description
Hi all 👋🏻
I've come across cases where I want a method to return a Range. In some cases, the Range should be empty.
I see from the documentation, that it's possible to initialise a null Range by passing in values where a is greater than b Range.new(1, -1)
.
I find this particular notation to be unclear, and likely to be discouraged by my team because it's unclear.
I'm opening this discussion to see if there's any interest in support for a simpler notation for null (empty) Ranges. Something like:
r = Range.new(nil) # notation not currently supported
r.size # => 0
r.max # => nil
r.min # => nil
r.each { puts "This is never called" }
Updated by zverok (Victor Shepelev) 7 months ago
What’s the expected semantics of this range?
There can be several options. Note that the behavior should be consistent/explainable in the context of other ranges (sometimes it makes sense to define the specialized behavior, but a very strong case for it should be done).
Basically, the two options you have currently:
- “The method usually returns a range of some type, I want a range of this type, but an empty (non-iterable) one.” It is easily represented by
val...val
(say, for numerics:0...0
). Itssize
would be0
,each
would do nothing. Itsbegin
/end
are notnil
, but depending on the logic of the program, it might be actually more consistent with the expectations of the method, and more reasonable to define; - “We don’t know where the range begins and where it ends, just that it is some Range”:
nil..nil
. It would havenil
forbegin
,end
andsize
, and can’t be iterated (= would throw an exception).
I think that reflecting upon which is more suitable for the further program and gives its the clearest semantics might be more useful than defining new kinds of the Range.