Reputation: 870
Hello need to change the keys of a hash inside an if block and append some value to the each key at each loop I have done it but it does work but keeps on changing with each run and returns different results.
assume the hash is called hash and I'm checking if it has any hashes inside than changing their key values
I have it as this
...
hash.each {|key,value|
if hash[key].is_a?(Hash)
hash[:"Match #{key}"] = hash[key]
hash.delete(key)
....
puts hash.keys
end
}
...
With this code segement the first run returns well but subsequent runs get all mixed up and give lots of values repeated with each giving different result.
like run 1 is
Match User gideon
assuming i have a User gideon key hash in the provided hash which is correct but it's very unpredictable
the 2nd run
Match User gideon
Match Match User gideon
Match Match Match User gideon
Match Match Match Match User gideon
Match Match Match Match Match User gideon
Match Match Match Match Match Match User gideon
so destroying everything Help appreciated
Upvotes: 1
Views: 717
Reputation: 110675
Suppose:
h = { :bacon=>"good", 3=>{:waffles=>"yum"}, :stack=>{"pancakes"=>"OK"} }
I assume you want to convert this to:
h = { :bacon=>"good", :"Match 3"=>{:waffles=>"yum"},
:"Match stack"=>{"pancakes"=>"OK"} }
Here's one way you can do that:
h.keys.each { |k| (h[:"Match #{k}"] = h.delete(k)) if h[k].is_a? Hash }
h
This example was inspired by the work of @muistooshort (a.k.a. μ).
Upvotes: 2
Reputation: 130
Your code does not run. Ruby says "RuntimeError: can't add a new key into hash during iteration
".
I would suggest you just make a new hash.
new_hash = {}
hash.each do |key,value|
if value.is_a?(Hash)
new_hash[:"Match #{key}"] = value
else
new_hash[key] = value
end
puts new_hash.keys
end
Upvotes: 2