How to recursively remove all keys with empty values from (YAML) hash?

前端 未结 6 1910
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 22:21

I have been trying to get rid of all hash keys in my YAML file that have empty (blank) values or empty hashes as values.

This earlier post helped me to get it almost

6条回答
  •  礼貌的吻别
    2021-01-04 22:36

    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
    

提交回复
热议问题