End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Array#shift
array.shift → object or nil
array.shift(n) → new_array
array.c
View on GitHub ↗
static VALUE
rb_ary_shift_m(int argc, VALUE *argv, VALUE ary)
{
VALUE result;
long n;
if (argc == 0) {
return rb_ary_shift(ary);
}
rb_ary_modify_check(ary);
result = ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
n = RARRAY_LEN(result);
rb_ary_behead(ary,n);
return result;
}
Removes and returns leading elements.
When no argument is given, removes and returns the first element:
Example
a = [:foo, 'bar', 2] a.shift # => :foo a # => ['bar', 2]
Returns nil if self is empty.
When positive Integer argument n is given, removes the first n elements; returns those elements in a new Array:
Example
a = [:foo, 'bar', 2] a.shift(2) # => [:foo, 'bar'] a # => [2]
If n is as large as or larger than self.length, removes all elements; returns those elements in a new Array:
Example
a = [:foo, 'bar', 2] a.shift(3) # => [:foo, 'bar', 2]
If n is zero, returns a new empty Array; self is unmodified.