instance method
Range#first
() -> Elem
(::Integer n) -> ::Array[Elem]
first → object
first(n) → array
range.c
View on GitHub ↗
static VALUE
range_first(int argc, VALUE *argv, VALUE range)
{
VALUE n, ary[2];
if (NIL_P(RANGE_BEG(range))) {
rb_raise(rb_eRangeError, "cannot get the first element of beginless range");
}
if (argc == 0) return RANGE_BEG(range);
rb_scan_args(argc, argv, "1", &n);
ary[0] = n;
ary[1] = rb_ary_new2(NUM2LONG(n));
rb_block_call(range, idEach, 0, 0, first_i, (VALUE)ary);
return ary[1];
}
With no argument, returns the first element of self, if it exists:
Example
(1..4).first # => 1 ('a'..'d').first # => "a"
With non-negative integer argument n given, returns the first n elements in an array:
Example
(1..10).first(3) # => [1, 2, 3] (1..10).first(0) # => [] (1..4).first(50) # => [1, 2, 3, 4]
Raises an exception if there is no first element:
Example
(..4).first # Raises RangeError