简体   繁体   中英

Change and edit the key of a Hash inside an if block

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

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

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 (aka μ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM