Misc #18984
closedDoc for Range#size for Float/Rational does not make sense
Description
When Range
consists of any Numeric, according to Official docs for Ruby-3.1.2, Range#size
should,
Returns the count of elements in self if both begin and end values are numeric;
Indeed, when Range
consists of only Integer
, this makes sense.
However, when the begin value of Range
is a Float
or Rational
, "the count of elements" does not make sense. Such Ranges are not iteratable, suggesting there are no such things as "elements":
(0.51..5.quo(2)).each{} # => TypeError
Yet, Range#size
of such Ranges returns an Integer
(0.51..5.quo(2)).size # => 2
It seems both begin and end values of a Range are rounded (Numeric#round
) to the nearest Integer before Range#size
is calculated.
If this is the specification, I suggest it should be clearly stated in the Official docs, avoiding the confusing expression "the count of elements", because "elements" are not unambiguously defined for Range of Float/Rational.
Updated by Eregon (Benoit Daloze) almost 2 years ago
- Assignee deleted (
core)
Updated by Eregon (Benoit Daloze) almost 2 years ago
Please do not assign ruby-core, that sends too many emails.
Updated by sawa (Tsuyoshi Sawada) almost 2 years ago
I think this is a bug. Since (0.51..5.quo(2)).count
raises a TypeError
and (0.51..5.quo(2)).size
is supposed to follow that, it should raise a TypeError
as well.
Updated by kyanagi (Kouhei Yanagita) 10 months ago
It seems that there is a similar issue with beginless ranges.
(..0).size # => Infinity
(..0).count # => Infinity
(..0).each {} # => can't iterate from NilClass (TypeError)
Is it reasonable to say the size is infinite even if it can't be iterated?
Updated by mame (Yusuke Endoh) 10 months ago
Discussed at the dev meeting. @matz (Yukihiro Matsumoto) said that he wanted to try to fix the behavior of Range#size instead of changing the document. If the incompatibilty is found significant, it will be reconsidered.
(0.51..5.quo(2)).size #=> TypeError
(..0).size #=> TypeError
Updated by kyanagi (Kouhei Yanagita) 10 months ago
I created a PR: https://github.com/ruby/ruby/pull/8663
What should we do about Range#count
?
(..0).count # => Infinity
(nil..nil).count # => Infinity
Updated by kyanagi (Kouhei Yanagita) 4 months ago
- Status changed from Open to Closed
Applied in changeset git|9f6deaa6888a423720b4b127b5314f0ad26cc2e6.
[Misc #18984] Raise TypeError from Range#size if the range is not iterable