Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Removes and returns leading elements.
When no argument is given, removes and returns the first element:
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:
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:
a = [:foo, 'bar', 2]
a.shift(3) # => [:foo, 'bar', 2]
If n is zero, returns a new empty Array; self is unmodified.
Related: push, pop, unshift.
 
               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;
}
            

Was this page useful?