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

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

    hash = {"x"=>{"m"=>{"n"=>{}}}, 'y' => 'content'}
    clean = proc{ |k,v| !v.empty? ? Hash === v ? v.delete_if(&clean) : false : true }
    hash.delete_if(&clean)
    #=> {"y"=>"content"} 
    

    or like @sawa suggested, you can use this proc

    clean = proc{ |k,v| v.empty? or Hash === v && v.delete_if(&clean) }
    

提交回复
热议问题