Removing all empty elements from a hash / YAML?

前端 未结 20 1694
礼貌的吻别
礼貌的吻别 2020-12-07 15:35

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

20条回答
  •  误落风尘
    2020-12-07 16:05

    You could add a compact method to Hash like this

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

    or for a version that supports recursion

    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
    

提交回复
热议问题