Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Array#shift
() -> Elem
(::int n) -> ::Array[Elem]
shift → object or nil
shift(count) → new_array or nil
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 from self.
With no argument, removes and returns one element, if available, or nil otherwise:
Example
a = [0, 1, 2, 3] a.shift # => 0 a # => [1, 2, 3] [].shift # => nil
With non-negative numeric argument count given, removes and returns the first count elements:
Example
a = [0, 1, 2, 3] a.shift(2) # => [0, 1] a # => [2, 3] a.shift(1.1) # => [2] a # => [3] a.shift(0) # => [] a # => [3]
If count is large, removes and returns all elements:
Example
a = [0, 1, 2, 3] a.shift(50) # => [0, 1, 2, 3] a # => []
If self is empty, returns a new empty array.
Related: see Methods for Deleting.