Removing all empty elements from a hash / YAML?

前端 未结 20 1684
礼貌的吻别
礼貌的吻别 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 15:53

    class Hash   
      def compact
        def _empty?(val)
          case val
          when Hash     then val.compact.empty?
          when Array    then val.all? { |v| _empty?(v) }
          when String   then val.empty?
          when NilClass then true
          # ... custom checking 
          end
        end
    
        delete_if { |_key, val| _empty?(val) }   
      end 
    end
    

提交回复
热议问题