shift(*args) public

Removes the first element of self and returns it (shifting all other elements down by one). Returns nil if the array is empty.

If a number n is given, returns an array of the first n elements (or less) just like array.slice!(0, n) does. With ary containing only the remainder elements, not including what was shifted to new_ary. See also Array#unshift for the opposite effect.

args = [ "-m", "-q", "filename" ]
args.shift  #=> "-m"
args #=> ["-q", "filename"]
args = [ "-m", "-q", "filename" ]
args.shift (2) #=> ["-m", "-q"]
args #=> ["filename"]
Show source
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);
 if (ARY_SHARED_P(ary)) {
 if (ARY_SHARED_OCCUPIED(ARY_SHARED(ary))) {
 setup_occupied_shared:
 ary_mem_clear(ary, 0, n);
 }
 ARY_INCREASE_PTR(ary, n);
 }
 else {
 if (RARRAY_LEN(ary) < ARY_DEFAULT_SIZE) {
 RARRAY_PTR_USE(ary, ptr, {
 MEMMOVE(ptr, ptr+n, VALUE, RARRAY_LEN(ary)-n);
 }); /* WB: no new reference */
 }
 else {
 ary_make_shared(ary);
 goto setup_occupied_shared;
 }
 }
 ARY_INCREASE_LEN(ary, -n);
 return result;
}
Register or log in to add new notes.
Default_avatar_30 nhance - April 1, 2010
Loader 3 thanks

Doesn't return nil on empty array when param is given

This does not return nil if the array is empty and n is given.

[].shift (2) # => []
a = []
a.shift (2) # => []
a # => []

AltStyle によって変換されたページ (->オリジナル) /