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

前端 未结 6 1911
没有蜡笔的小新
没有蜡笔的小新 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:41

    Just a bit related thing. If you want to delete specified keys from nested hash:

    def find_and_destroy(*keys)
        delete_if{ |k, v| (keys.include?(k.to_s) ? true : ( (v.each { |vv| vv = vv.find_and_destroy(*keys) }) if v.instance_of?(Array) ;  (v.each { |vv| vv = vv.find_and_destroy(*keys) }) if v.instance_of?(Hash); false) )}
    end
    

    .You can also customize it further

提交回复
热议问题