Removing all empty elements from a hash / YAML?

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

    our version: it also cleans the empty strings and nil values

    class Hash
    
      def compact
        delete_if{|k, v|
    
          (v.is_a?(Hash) and v.respond_to?('empty?') and v.compact.empty?) or
              (v.nil?)  or
              (v.is_a?(String) and v.empty?)
        }
      end
    
    end
    

提交回复
热议问题