Removing all empty elements from a hash / YAML?

前端 未结 20 1683
礼貌的吻别
礼貌的吻别 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:52

    Here is something I have:

    # recursively remove empty keys (hashes), values (array), hashes and arrays from hash or array
    def sanitize data
      case data
      when Array
        data.delete_if { |value| res = sanitize(value); res.blank? }
      when Hash
        data.delete_if { |_, value| res = sanitize(value); res.blank? }
      end
      data.blank? ? nil : data
    end
    

提交回复
热议问题