public Method

Array.compact!

array.compact!       array  or  nil

Removes nil elements from array. Returns nil if no changes were made.

[ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
[ "a", "b", "c" ].compact!           #=> nil

Source Code

/* 
*  call-seq:
*     array.compact!    ->   array  or  nil
*
*  Removes +nil+ elements from array.
*  Returns +nil+ if no changes were made.
*
*     [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
*     [ "a", "b", "c" ].compact!           #=> nil
*/

static VALUE
rb_ary_compact_bang(ary)
   VALUE ary;
{
   VALUE *p, *t, *end;

   rb_ary_modify(ary);
   p = t = RARRAY(ary)->ptr;
   end = p + RARRAY(ary)->len;

   while (t < end) {
       if (NIL_P(*t)) t++;
       else *p++ = *t++;
   }
   if (RARRAY(ary)->len == (p - RARRAY(ary)->ptr)) {
       return Qnil;
   }
   RARRAY(ary)->len = RARRAY(ary)->aux.capa = (p - RARRAY(ary)->ptr);
   REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len);

   return ary;
}
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.