删除具有空数组的键

时间:2018-10-03 04:17:53

标签: arrays ruby hash

我需要删除具有空数组的子键:

  networks = {
    "CL1": {
      "192.168.200.0/24": [

      ],
      "192.168.56.0/24": [
        "192.168.56.57",
        "192.168.56.84",
      ]
    },
    "CL2": {
      "192.168.222.0/24": [
        "192.168.222.224",
      ]
    }
  }

  networks = {
    "CL1": {
      "192.168.56.0/24": [
        "192.168.56.57",
        "192.168.56.84",
      ]
    },
    "CL2": {
      "192.168.222.0/24": [
        "192.168.222.224",
      ]
    }
  }

是否可以删除具有空数组的关键元素?

2 个答案:

答案 0 :(得分:2)

networks.transform_values { |v| v.reject { |_,a| a.empty? } }
  #=> {:CL1=>{:"192.168.56.0/24"=>["192.168.56.57", "192.168.56.84"]},
  #    :CL2=>{:"192.168.222.0/24"=>["192.168.222.224"]}}

请参见Hash#transform_valuesHash#reject。前者在MRI v2.4中首次亮相。

答案 1 :(得分:0)

您可以通过过滤内部哈希中的空键来创建新密钥。

networks = networks.map {|key, inner_hash|  [key, inner_hash.select{|k, v| v.any?}.to_h]}
                   .to_h
puts networks
# {
#     :CL1 => {
#         :"192.168.56.0/24" => ["192.168.56.57", "192.168.56.84"]
#     }, 
#     :CL2 => {
#         :"192.168.222.0/24" => ["192.168.222.224"]
#     }
# }