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!
, orreject!(&: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.
Posted by Emanuel to makandra dev (2022-06-01 05:39)