APIdock / Ruby
/
method

compact!

ruby latest stable - Class: Array
compact!()
public

Removes nil elements from the array.

Returns nil if no changes were made, otherwise returns the array.

[ "a", nil, "b", nil, "c" ].compact!  #=> [ "a", "b", "c" ]
[ "a", "b", "c" ].compact!  #=> nil
static VALUE
rb_ary_compact_bang(VALUE ary)
{
 VALUE *p, *t, *end;
 long n;
 rb_ary_modify(ary);
 p = t = (VALUE *)RARRAY_CONST_PTR(ary); /* WB: no new reference */
 end = p + RARRAY_LEN(ary);
 while (t < end) {
 if (NIL_P(*t)) t++;
 else *p++ = *t++;
 }
 n = p - RARRAY_CONST_PTR(ary);
 if (RARRAY_LEN(ary) == n) {
 return Qnil;
 }
 ary_resize_smaller(ary, n);
 return ary;
}

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