如何从(YAML)哈希中递归删除所有具有空值的键?
我一直在尝试删除 YAML 文件中具有空(空白)值或空哈希值的所有哈希键。
这篇之前的帖子帮助我几乎正确,但是每当有足够深的嵌套时,递归单行代码就会在我的 YAML 转储中留下空哈希值。
我非常感谢对此的任何帮助。谢谢!
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)
实际输出
{"x"=>{"m"=>{}}, "y"=>"content"}
期望输出
{"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"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为这是最正确的版本:
I think this the most correct version:
我知道这个线程有点旧,但我想出了一个更好的解决方案,支持多维哈希。它使用delete_if?除了它的多维性之外,默认情况下会清除任何具有空值的内容,并且如果传递了一个块,它将通过其子级向下传递。
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.
只是有点相关的事情。如果你想从嵌套哈希中删除指定的键:
。你也可以进一步自定义它
Just a bit related thing. If you want to delete specified keys from nested hash:
.You can also customize it further
或者像@sawa建议的那样,你可以使用这个过程
or like @sawa suggested, you can use this proc
这是一个更通用的方法:
Here's a more generic method: