How would I go about removing all empty elements (empty list items) from a nested Hash or YAML file?
If you are using Rails
(or a standalone ActiveSupport
), starting from version 6.1
, there is a compact_blank method which removes blank
values from hashes.
It uses Object#blank? under the hood for determining if an item is blank.
{ a: "", b: 1, c: nil, d: [], e: false, f: true }.compact_blank
# => { b: 1, f: true }
Here is a link to the docs and a link to the relative PR.
A destructive variant is also available. See Hash#compact_blank!.
If you need to remove only nil
values,
please, consider using Ruby build-in Hash#compact and Hash#compact! methods.
{ a: 1, b: false, c: nil }.compact
# => { a: 1, b: false }