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

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

    I think this the most correct version:

    h = {a: {b: {c: "",}, d:1}, e:2, f: {g: {h:''}}}
    p = proc do |_, v|
      v.delete_if(&p) if v.respond_to? :delete_if
      v.nil? || v.respond_to?(:"empty?") && v.empty?
    end
    h.delete_if(&p)
    #=> {:a=>{:d=>1}, :e=>2}
    

提交回复
热议问题