Project

General

Profile

Actions

Feature #20483

open

More intuitive initialisation of null Range

Added by bodacious (Gavin Morrice) 7 months ago. Updated 7 months ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:117834]

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). Its size would be 0, each would do nothing. Its begin/end are not nil, 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 have nil for begin, end and size, 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.

Actions

Also available in: Atom PDF

Like0
Like0