Posted about 1 month ago. Visible to the public.

Rails: Removing nil or blank values from an array

Removing nil values from an array

To remove from an existing array:

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

You may also use the splat operator to ignore nil values when constructing the array:

['foo', *nil] # => ['foo']

Removing blank values from an array

In Rails >= 6.1

['foo', nil, '', [], {}].compact_blank # => ['foo']

Any Rails version

['foo', nil, '', [], {}].reject(&:blank?) # => ['foo']

(This is actually what compact_blank does Archive .)

Note that 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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Emanuel De
Last edit:
about 1 month ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more