Rails: Remove Blank Values from Collections

Updated . Posted . Visible to the public.

tl;dr

Since Rails 6.1+ you can use .compact_blank or .compact_blank! to remove blank values from collections (e.g. arrays).

Remove nil values from an array

['foo', nil].compact
# => ['foo']

# You can use the splat operator to ignore nil values when constructing an array
['foo', *nil]
# => ['foo']

Remove blank values from collections

Array

array = [1, "", nil, 2, " ", [], {}, false, true]

# Any Rails version
array.reject(&:blank?)
# => [1, 2, true]

# Since Rails 6.1+
array.compact_blank
# => [1, 2, true]

Hash

hash = { a: 1, b: "", c: nil, d: 2, e: " ", f: [], g: {}, h: false, i: true }

# Any Rails version
hash.reject { |key, value| value.blank? }
# => { a: 1, d: 2, i: true }

# Since Rails 6.1+
hash.compact_blank
# => { a: 1, d: 2, i: true }

Hint

This is actually what compact_blank does Show archive.org snapshot .

Warning

There are bang variants of each method compact!, compact_blank!, or reject!(&:blank?).

They modify the array in place, so be careful not to modify an array that you received as a method argument as the caller might not expect changes to it.

Last edit
Julian
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2022-06-01 05:39)