Project

General

Profile

Actions

Misc #17637

open

Endless ranges with `nil` boundary weird behavior

Added by gud (gud gud) almost 4 years ago. Updated almost 4 years ago.

Status:
Open
Assignee:
-
[ruby-core:102558]

Description

Basically it's about this https://andycroll.com/ruby/watch-out-for-nils-in-ranges/

Since Ruby 2.6 we have this weird syntax (0..nil) which is really really bug prone

e.g. we have dynamic upper boundary like

lower = 0
upper = some_method(arg1, arg2)

(lower..upper).each do { |s| some_method2(s) }

We rarely do nil checks in Ruby so it's really easy to have Infinity loop in the end.
Previous Argument error was more intuitive since it throws exception instead of silently looping forever.

  • some additional strange behavior:
(0..nil).count
=> Infinity

(0..Float::INFINITY).count
=> hangs, I guess same infinity loop

Having explicit parameter Float::INFINITY (as in previous versions) looks more like a proper design instead of allowing nil as a valid parameter.

You may think of it as I would like to have a range from 0 to nothing, what is it actually ?
And I guess the answer is Nothing.
Fixing (0..Float::INFINITY).count this case it also important I believe.

Tested on ruby 2.7.1p83


Related issues 1 (0 open1 closed)

Related to Ruby master - Bug #14845: Endless Range with nilClosedmatz (Yukihiro Matsumoto)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0