gregates gregates - 26 days ago 11
Ruby Question

is there an equivalent of Array#compact for empty elements?

As we all know,

Array#compact
removes
nil
elements from the array.

array.reject { |element| element.empty? }


would remove empty elements like
[]
(in rails you could also do
#blank?
to get rid of empty elements and
nil
elements).

Is there a shorthand method for removing empty/blank elements like
Array#compact
? Or is using
Array#reject
my best bet?

I haven't seen the "empty" equivalent of
#compact
, if there is one. But maybe I'm just overlooking it.

Answer

I believe your best bet is:

array.reject &:empty?

In Rails you can write:

array.reject &:blank?

As pointed out by mu is too short, in Rails you can also write:

array.select &:present?
Comments