Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Range#size
size → non_negative_integer or Infinity or nil
range.c
View on GitHub ↗
static VALUE
range_size(VALUE range)
{
VALUE b = RANGE_BEG(range), e = RANGE_END(range);
if (rb_obj_is_kind_of(b, rb_cNumeric)) {
if (rb_obj_is_kind_of(e, rb_cNumeric)) {
return ruby_num_interval_step_size(b, e, INT2FIX(1), EXCL(range));
}
if (NIL_P(e)) {
return DBL2NUM(HUGE_VAL);
}
}
else if (NIL_P(b)) {
if (rb_obj_is_kind_of(e, rb_cNumeric)) {
return DBL2NUM(HUGE_VAL);
}
}
return Qnil;
}
Returns the count of elements in self if both begin and end values are numeric; otherwise, returns nil:
Example
(1..4).size # => 4 (1...4).size # => 3 (1..).size # => Infinity ('a'..'z').size #=> nil
Related: Range#count.