访问和更新散列哈希Ruby的值

时间:2017-02-18 14:38:06

标签: arrays ruby hash

我有这个庞大的嵌套Ruby哈希:

hash_filter = {
  "m-ct-filter-bot"=>{
    "parameters"=>{
      "filter_action"=>"keep", "filter_key"=>"classification.identifier",
      "filter_regex"=>nil, "filter_value"=>""
    },
    "group"=>"Expert", "name"=>"Filter", "module"=>"bots.experts.filter.expert",
    "description"=>"modified by mf370"
  },
  "m-vision-filter-bot"=>{
    "parameters"=>{
      "filter_action"=>"keep", "filter_key"=>"classification.identifier",
      "filter_regex"=>nil, "filter_value"=>""
    },
    "group"=>"Expert", "name"=>"Filter", "module"=>"bots.experts.filter.expert",
    "description"=>"modified by mf370"
  },
  "m-tele-filter-bot"=>{
    "parameters"=>{
      "filter_action"=>"keep", "filter_key"=>"classification.identifier",
      "filter_regex"=>nil, "filter_value"=>""
    },
    "group"=>"Expert", "name"=>"Filter", "module"=>"bots.experts.filter.expert",
    "description"=>"modified by mf370"
  }
}

这个数组:

array_id = ["ct","vision","tele"]

我尝试使用"filter_value"的值更新每个嵌套哈希上的键array_id上的值。为了在相应的哈希上有filter_value => ctfilter_value => visionfilter_value => tele

我有以下代码:

array_id.each do |id|
  hash_filter.each_pair do |key, value|
    value["parameters"]["filter_value"] = id
    end
  end

但是,当我运行此代码时,密钥filter_value始终使用array_id的最后一个值进行更新,这意味着我的所有哈希值都具有相同的值filter_value => tele。< / p>

我没有收到任何错误,只是输出不是我所期待的。 你能帮助我吗? :)

谢谢!

1 个答案:

答案 0 :(得分:3)

这是因为你迭代array_id所以你的哈希值总是与这个数组的最后一个元素相同。有很多变种可以解决这个问题。但下次,你应该更加专心;) 感谢@CarySwoveland:

a_id = array_id.dup
hash_filter.each do |_key, value|
   value["parameters"]["filter_value"] = a_id.shift
end
hash_filter

此外,对于Ruby v2.4.0,您可以使用新方法:#transform_values

hash_filter.transform_values.with_index do |value, ind|
   value["parameters"]["filter_value"] = array_id[ind]
end
hash_filter