compact_blank (Rails 6.1+)
If you are using Rails
(or a standalone ActiveSupport
), starting from version 6.1
, there is a compact_blank
method that removes blank
values from arrays.
It uses Object#blank?
under the hood for determining if an item is blank.
["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"].compact_blank
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
[1, "", nil, 2, " ", [], {}, false, true].compact_blank
# => [1, 2, true]
Here is a link to the docs and a link to the relative PR.
A destructive variant is also available. See Array#compact_blank!
.
If you have an older version of Rails
, check compact_blank
internal implementation.
It is not so complex to backport it.
def compact_blank
reject(&:blank?)
end
If you need to remove only nil
values, consider using Ruby build-in Array#compact
and Array#compact!
methods.
["a", nil, "b", nil, "c", nil].compact
# => ["a", "b", "c"]