Removing all empty elements from a hash / YAML?

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

    I know this thread is a bit old but I came up with a better solution which supports Multidimensional hashes. It uses delete_if? except its multidimensional and cleans out anything with a an empty value by default and if a block is passed it is passed down through it's children.

    # Hash cleaner
    class Hash
        def clean!
            self.delete_if do |key, val|
                if block_given?
                    yield(key,val)
                else
                    # Prepeare the tests
                    test1 = val.nil?
                    test2 = val === 0
                    test3 = val === false
                    test4 = val.empty? if val.respond_to?('empty?')
                    test5 = val.strip.empty? if val.is_a?(String) && val.respond_to?('empty?')
    
                    # Were any of the tests true
                    test1 || test2 || test3 || test4 || test5
                end
            end
    
            self.each do |key, val|
                if self[key].is_a?(Hash) && self[key].respond_to?('clean!')
                    if block_given?
                        self[key] = self[key].clean!(&Proc.new)
                    else
                        self[key] = self[key].clean!
                    end
                end
            end
    
            return self
        end
    end
    

提交回复
热议问题