Read more

Rails: Remove Blank Values from Collections

Emanuel
June 01, 2022Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot
Emanuel
June 01, 2022Software engineer at makandra GmbH
Posted by Emanuel to makandra dev (2022-06-01 07:39)