简体   繁体   English

在if块中更改和编辑哈希的键

[英]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. 您好需要在if块中更改哈希的键,并在每次执行的循环中将一些值附加到每个键上,但是它确实有效,但是每次运行都会不断更改并返回不同的结果。

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 像运行1是

       Match User gideon

assuming i have a User gideon key hash in the provided hash which is correct but it's very unpredictable 假设我在提供的哈希中有一个用户gideon密钥哈希,这是正确的,但是非常不可预测

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 ". Ruby说:“ 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 μ). 这个例子的灵感来自@muistooshort(akaμ)的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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