Compact Disc

Use compact_blank to remove empty strings from Arrays and Hashes

Active Support is a library of “useful” things that support (!) the other parts of Rails. It includes ways to extend the base Ruby classes, such as Hash, String and Integer.

Even the most experienced Rails developer is constantly finding helpful methods in Active Support. And useful methods are continually being added in new versions of the library.

We often have to clean up the values ofHashes and Arrays when parsing parameters, or if our code accepts complex input. Ruby provides the #compact method to remove nil values from an array and (since 2.4) has provided the same #compact method for Hash.

In addition to nil often we’re often looking to remove empty strings or other “blank” objects as well.

Instead of…

…manually looping through the values of a hash to remove nils and empty strings:

[1, nil, 3, “”, []].compact
#=> [1, “3”, “”, []]

[1, nil, 3, “”, []].reject { |e| e.nil? || e&.empty? }
#=> [1, “3”]

[1, nil, 3, “”, []].reject(&:blank?)
#=> [1, “3”]

{1 => 2, 2 => nil, 3 => 4, 4 => “”, 5 => []}.compact
#=> {1 => 2, “3” => “4”, 4 => “”, 5 => []}

{1 => 2, 2 => nil, 3 => 4, 4 => “”, 5 => []}.reject { |_, v| v.nil? || v&.empty? }
#=> {1 => 2, “3” => “4”}

{1 => 2, 2 => nil, 3 => 4, 4 => “”, 5 => []}.reject { |_, v| v.blank? }
#=> {1 => 2, “3” => “4”}

Use…

…Active Support’s #compact_blank method:

[1, nil, 3, “”, []].compact_blank
#=> [1, “3”]

result = {1 => 2, 2 => nil, 3 => 4, 4 => “”, 5 => []}.compact_blank
#=> {1 => 2, “3” => “4”}

The #compact_blank method was added in Rails 6.1.

Why?

This is a “useful Rails thing” that feels like it’s part of Ruby once you’re used to it. Many of the core extensions in Active Support have that feeling in common. It reads a lot better than the #reject-based versions.

Why not?

Some folks resent the intrusion of the framework into the base concepts of the language.

However, there have definitely been cases where Ruby has adopted an “Active Support-ism”. Hash#compact was in Rails long before it was in the base language.


last updated on 20 Sep 2021 by @andycroll

photo by
Jan Huber

Don’t miss my next post, sign up to the One Ruby Thing email and get my next post in your inbox.

Don’t miss my next post, sign up to the One Ruby Thing email and get my next post in your inbox.