public Method

Array.shift

array.shift      obj or nil

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

args = [ "-m", "-q", "filename" ]
args.shift   #=> "-m"
args         #=> ["-q", "filename"]

Source Code

/*
*  call-seq:
*     array.shift   ->   obj or nil
*  
*  Returns the first element of <i>self</i> and removes it (shifting all
*  other elements down by one). Returns <code>nil</code> if the array
*  is empty.
*     
*     args = [ "-m", "-q", "filename" ]
*     args.shift   #=> "-m"
*     args         #=> ["-q", "filename"]
*/

VALUE
rb_ary_shift(ary)
   VALUE ary;
{
   VALUE top;

   rb_ary_modify_check(ary);
   if (RARRAY(ary)->len == 0) return Qnil;
   top = RARRAY(ary)->ptr[0];
   if (RARRAY_LEN(ary) < ARY_DEFAULT_SIZE && !FL_TEST(ary, ELTS_SHARED)) {
       MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+1, VALUE, RARRAY_LEN(ary)-1);
   }
   else {
       if (!FL_TEST(ary, ELTS_SHARED)) {
           RARRAY(ary)->ptr[0] = Qnil;
       }
       ary_make_shared(ary);
       RARRAY(ary)->ptr++;            /* shift ptr */
   }
   RARRAY(ary)->len--;

   return top;
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.