Removing all empty elements from a hash / YAML?

前端 未结 20 1638
礼貌的吻别
礼貌的吻别 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:03

    I believe it would be best to use a self recursive method. That way it goes as deep as is needed. This will delete the key value pair if the value is nil or an empty Hash.

    class Hash
      def compact
        delete_if {|k,v| v.is_a?(Hash) ? v.compact.empty? : v.nil? }
      end
    end
    

    Then using it will look like this:

    x = {:a=>{:b=>2, :c=>3}, :d=>nil, :e=>{:f=>nil}, :g=>{}}
    # => {:a=>{:b=>2, :c=>3}, :d=>nil, :e=>{:f=>nil}, :g=>{}} 
    x.compact
    # => {:a=>{:b=>2, :c=>3}}
    

    To keep empty hashes you can simplify this to.

    class Hash
      def compact
        delete_if {|k,v| v.compact if v.is_a?(Hash); v.nil? }
      end
    end
    

提交回复
热议问题