且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何递归地从(YAML)散列中删除所有具有空值的键?

更新时间:2023-02-23 11:38:42

  class Hash 
def delete_blank
delete_if {| k,v | v.empty?或者v.instance_of?(哈希)&& v.delete_blank.empty?}
end
end

p hash.delete_blank
#=> {y=>content}


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 right, but the recursive one-liner leaves my YAML dump with empty hashes whenever there is sufficiently deep nesting.

I would really appreciate any help on this. Thanks!

proc = Proc.new { |k, v| (v.kind_of?(Hash) && !v.empty? ) ? (v.delete_if(&proc); nil) : v.blank? }

hash = {"x"=>{"m"=>{"n"=>{}}}, 'y' => 'content'}
hash.delete_if(&proc)

Actual output

 {"x"=>{"m"=>{}}, "y"=>"content"} 

Desired output

{"y"=>"content"}

class Hash
  def delete_blank
    delete_if{|k, v| v.empty? or v.instance_of?(Hash) && v.delete_blank.empty?}
  end
end

p hash.delete_blank
# => {"y"=>"content"}