mf370
mf370

Reputation: 331

Access and update value in hash of hashes Ruby

I have this massive nested Ruby hash:

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. In order to have filter_value => ct, filter_value => vision, filter_value => tele on the corresponding hash.

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.

I'm not getting any errors, is just the output is not what I was expecting. Can you guys help me out? :)

Thank you!!

Upvotes: 1

Views: 1380

Answers (1)

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

It's happens cause you iterate array_id so your hash-value always be the same as last element of this array. There are to many variant to solve this. But next time, you should be more attentive ;) Thanks to @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

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

Upvotes: 3

Related Questions