Removing all empty elements from a hash / YAML?

前端 未结 20 1519
礼貌的吻别
礼貌的吻别 2020-12-07 15:35

How would I go about removing all empty elements (empty list items) from a nested Hash or YAML file?

20条回答
  •  时光说笑
    2020-12-07 16:04

    compact_blank (Rails 6.1+)

    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 }
    

提交回复
热议问题