instance method
Range#size
() -> (::Integer | ::Float | nil)
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_INTEGER_TYPE_P(b)) {
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);
}
}
if (!discrete_object_p(b)) {
CANT_ITERATE_FROM(b);
}
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
If self is not iterable, raises an exception:
Example
(0.5..2.5).size # TypeError (..1).size # TypeError
Related: Range#count.
Ruby version changes
-
3.4
-
Range#sizenow raisesTypeErrorif the range is not iterable. [Misc #18984]
-