Rails 6.1 adds compact_blank

Rails 6.1.0 adds compact_blank and compact_blank! to ActiveSupport which makes it easier for removing blank values from an Enumerable / ActionController::Parameters.

Before Rails 6.1

Removing blank values from an array:

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

Removing blank values from a hash:

{ a: nil, b: '', c: [], d: 1 }.reject { |_, value| value.blank? }
# => { d: 1 }

Rails 6.1

Removing blank values from an array:

[nil, 1, '', :foo].compact_blank
# => [1, :foo]

You can also use compact_blank! which mutates its receiver:

a = [1, "", nil, 2, " ", [], {}, false, true]
a.compact_blank!
# =>  [1, 2, true]

Removing blank values from a hash:

{ a: nil, b: '', c: [], d: 1 }.compact_blank
# => { d: 1 }

Using compact_blank!:

h = { a: "", b: 1, c: nil, d: [], e: false, f: true }
h.compact_blank!
# => { b: 1, f: true }

Check out the pull request to see the implementation.

Written on May 26, 2021

Share: