Remove blank values easily in Rails 6.1

hmtanbir

Hasan Tanbir

Posted on May 30, 2021

Remove blank values easily in Rails 6.1

Rails 6.1 adds compact_blank and compact_blank! methods to ActiveSupport. It makes easier for removing blank or nil values from an Enumerable ActionController::Parameters.

Here is the pull request.

Before Rails 6.1.0

We can remove blank values from an array as like:

[1,nil,'',:bar].reject(&:blank?)
# [1,:bar]
Enter fullscreen mode Exit fullscreen mode

We can remove blank values from a hash as like:

{ x: nil, y:[], z: :bar }.reject{|key,value| value.blank? }
# { :z => :bar }
Enter fullscreen mode Exit fullscreen mode

After Rails 6.1

we can use compact_blank and compact_blank!:

Array:

[1,nil,'',:bar].compact_blank
# [1,:bar]
Enter fullscreen mode Exit fullscreen mode

Hash:

{ x: nil, y:[], z: :bar }.compact_blank
# { :z => :bar }
Enter fullscreen mode Exit fullscreen mode

We can use compact_blank! which mutates it's receiver:

Array:

array = [1, "", nil,2, " ", [], {}, true, false]
array.compact_blank!
# [1,2,true]
Enter fullscreen mode Exit fullscreen mode

Hash:

hash = { a: 1, b: "", c: nil, d:"string", e:" ", f:[], g:{}, h: true, i: false }
hash.compact_blank!

# { :a => 1, :d => "string", :h => true }
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
hmtanbir
Hasan Tanbir

Posted on May 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related