Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Array#compact
() -> ::Array[Elem]
compact → new_array
array.c
View on GitHub ↗
static VALUE
rb_ary_compact(VALUE ary)
{
ary = rb_ary_dup(ary);
rb_ary_compact_bang(ary);
return ary;
}
Returns a new array containing only the non-nil elements from self; element order is preserved:
Example
a = [nil, 0, nil, false, nil, '', nil, [], nil, {}] a.compact # => [0, false, "", [], {}]
Related: Array#compact!; see also Methods for Deleting.