compact!()
public
Removes nil elements from array. Returns nil if no
changes were made.
[ "a", nil, "b", nil, "c" ].compact!
[ "a", "b", "c" ].compact!
Show source
static VALUE
rb_ary_compact_bang(VALUE ary)
{
VALUE *p, *t, *end;
long n;
rb_ary_modify(ary);
p = t = RARRAY_PTR(ary);
end = p + RARRAY_LEN(ary);
while (t < end) {
if (NIL_P(*t)) t++;
else *p++ = *t++;
}
n = p - RARRAY_PTR(ary);
if (RARRAY_LEN(ary) == n) {
return Qnil;
}
ARY_SET_LEN(ary, n);
if (n * 2 < ARY_CAPA(ary) && ARY_DEFAULT_SIZE * 2 < ARY_CAPA(ary)) {
ary_resize_capa(ary, n * 2);
}
return ary;
}