Before Rails 6 we used to remove the blank values from Array and Hash by using other available methods.
Before:
[...].delete_if(&:blank?)
{....}.delete_if { |_k, v| v.blank? }
OR
[...].reject(&:blank?)
...
From now, Rails 6.1.3.1
onwards you can use the module Enumerable’s compact_blank
and compact_blank!
methods.
Now we can use:
[1, "", nil, 2, " ", [], {}, false, true].compact_blank
=> [1, 2, true]
['', nil, 8, [], {}].compact_blank
=> [8]
{ a: "", b: 1, c: nil, d: [], e: false, f: true }.compact_blank
=> {:b=>1, :f=>true}
The method compact_blank!
is a destructive method (handle with care) for compact_blank
.
As a Rails developer, I am grateful for this method because there are many scenarios where we find ourselves replicating this code.