The Range
class of Ruby allows developers to work with sequences of values conveniently.
Ranges in Ruby can be created using the ..
(inclusive) and ...
(exclusive) notations, where ..
includes the end value, and ...
excludes it.
One commonly used method associated with ranges is size
, which returns the number of elements in the range, including both the start and end points.
However, a bug related to Rational endpoints in the size
method has been identified and addressed in the upcoming Ruby 3.3 release.
Before
A bug in versions prior to 3.3 causes incorrect behavior when the endpoint is a Rational number. Let’s illustrate this with examples:
In the above example, we create a range from 10 to 15.5(exclusive) with a Rational endpoint. The each
method correctly iterates over the range, printing 10, 11, 12, 13, 14 and 15.
However, when we query the size using size
method, the expected result of 6
is not returned; instead, an incorrect size of 5
is reported.
After
In Ruby 3.3, the bug related to Rational endpoints in the size method has been addressed.
The fix ensures that the size method correctly accounts for the endpoint, providing an accurate count of elements within the range. Let’s revisit the example:
With the bugfix in Ruby 3.3, the size
method now returns the expected result of 6
, including the Rational endpoint in the count.
To know more about this bugfix, please refer to this PR.