Posted 3 months 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:

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

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

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

Removing blank values from an array

In Rails >= 6.1

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

Any Rails version

Copy
['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.

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Emanuel De
Last edit:
3 months 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