从哈希/YAML 中删除所有空元素? [英] Removing all empty elements from a hash / YAML?

查看:34
本文介绍了从哈希/YAML 中删除所有空元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从嵌套的 Hash 或 YAML 文件中删除所有空元素(空列表项)?

How would I go about removing all empty elements (empty list items) from a nested Hash or YAML file?

推荐答案

你可以像这样给 Hash 添加一个紧凑的方法

You could add a compact method to Hash like this

class Hash
  def compact
    delete_if { |k, v| v.nil? }
  end
end

或支持递归的版本

class Hash
  def compact(opts={})
    inject({}) do |new_hash, (k,v)|
      if !v.nil?
        new_hash[k] = opts[:recurse] && v.class == Hash ? v.compact(opts) : v
      end
      new_hash
    end
  end
end

这篇关于从哈希/YAML 中删除所有空元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆