[英]Access and update value in hash of hashes Ruby
I have this massive nested 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"
}
}
And this array: 和这个数组:
array_id = ["ct","vision","tele"]
I'm trying to update the value on the key "filter_value"
on each nested hash with the values of the array_id
. 我正在尝试使用array_id
的值更新每个嵌套哈希上键"filter_value"
的值。 In order to have filter_value => ct
, filter_value => vision
, filter_value => tele
on the corresponding hash. 为了使filter_value => ct
, filter_value => vision
, filter_value => tele
在相应的哈希上。
I have the following code: 我有以下代码:
array_id.each do |id|
hash_filter.each_pair do |key, value|
value["parameters"]["filter_value"] = id
end
end
However, when I run this code the key filter_value
is updated ALWAYS with the last value of the array_id
, which means that all my hashes will have the same value filter_value => tele
. 但是,当我运行此代码时,关键filter_value
总是用array_id
的最后一个值更新,这意味着我所有的哈希值将具有相同的值filter_value => tele
。
I'm not getting any errors, is just the output is not what I was expecting. 我没有任何错误,只是输出不是我所期望的。 Can you guys help me out? 你们能帮我吗? :) :)
Thank you!! 谢谢!!
It's happens cause you iterate array_id
so your hash-value always be the same as last element of this array. 发生这种情况的原因是您迭代了array_id
因此您的哈希值始终与此数组的最后一个元素相同。 There are to many variant to solve this. 有很多变体来解决这个问题。 But next time, you should be more attentive ;) Thanks to @CarySwoveland: 但是下一次,您应该更加专心;)感谢@CarySwoveland:
a_id = array_id.dup
hash_filter.each do |_key, value|
value["parameters"]["filter_value"] = a_id.shift
end
hash_filter
Also, for Ruby v2.4.0 you can use new method: #transform_values
另外,对于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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.