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]
We can remove blank values from a hash as like:
{ x: nil, y:[], z: :bar }.reject{|key,value| value.blank? }
# { :z => :bar }
After Rails 6.1
we can use compact_blank
and compact_blank!
:
Array:
[1,nil,'',:bar].compact_blank
# [1,:bar]
Hash:
{ x: nil, y:[], z: :bar }.compact_blank
# { :z => :bar }
We can use compact_blank!
which mutates it's receiver:
Array:
array = [1, "", nil,2, " ", [], {}, true, false]
array.compact_blank!
# [1,2,true]
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 }
Top comments (0)