Removing all empty elements from a hash / YAML?

前端 未结 20 1716
礼貌的吻别
礼貌的吻别 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 15:46

    The recursive version of https://stackoverflow.com/a/14773555/1519240 works, but not with HashWithIndifferentAccess or other classes that are kind of Hash..

    Here is the version I am using:

    def recursive_compact
      inject({}) do |new_hash, (k,v)|
        if !v.nil?
          new_hash[k] = v.kind_of?(Hash) ? v.recursive_compact : v
        end
        new_hash
      end
    end
    

    kind_of?(Hash) will accept more classes that are like a Hash.

    You can also replace inject({}) by inject(HashWithIndifferentAccess.new) if you want to access the new hash using both symbol and string.

提交回复
热议问题