In Ruby, a Range
is an object that represents a range of values with a defined beginning and end. It is a fundamental data structure used to express a sequence or span between two values, whether they are numeric, alphabetical, or even dates.
We have two ways to define ranges.
Ruby Range#size method
Returns the number of elements in the range. Both the begin and the end of the Range must be Numeric, otherwise nil is returned.
Before
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”.
Yet, Range#size
of such Ranges returns an Integer
and returns an Infinity
for beginless
It seems both begin and end values of a Range
are rounded (Numeric#round
) to the nearest Integer before Range#size
is calculated.
After
In Ruby 3.4, Range#size raises TypeError if the range is not iterable.