Compact Disc

image by Jan Huber

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.

RailsConf 2024

I'm co-chairing RailsConf 2024 in Detroit May 7–9. Come and join us 

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.

Brighton Ruby 2024

Still running UK’s friendliest, Ruby event on Friday 28th June. Ice cream + Ruby 


Last updated on September 20th, 2021 by @andycroll

An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.