繁体   English   中英

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

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

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

假设哈希称为哈希,并且我正在检查哈希是否内部包含任何哈希,而不是更改其键值

我有这个

    ...

    hash.each {|key,value|
        if hash[key].is_a?(Hash)
           hash[:"Match #{key}"] = hash[key]
           hash.delete(key)
           ....
           puts hash.keys
        end
 }

  ...

使用此代码段,第一次运行返回良好,但随后的运行混合在一起并给出大量重复的值,每次给出不同的结果。

像运行1是

       Match User gideon

假设我在提供的哈希中有一个用户gideon密钥哈希,这是正确的,但是非常不可预测

第二轮

             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

所以销毁一切,帮助感激

您的代码无法运行。 Ruby说:“ RuntimeError: can't add a new key into hash during iteration ”。

我建议您只是做一个新的哈希。

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

假设:

h = { :bacon=>"good", 3=>{:waffles=>"yum"}, :stack=>{"pancakes"=>"OK"} }

我假设您要将其转换为:

h = { :bacon=>"good", :"Match 3"=>{:waffles=>"yum"},
      :"Match stack"=>{"pancakes"=>"OK"} }

这是您可以执行此操作的一种方法:

h.keys.each { |k| (h[:"Match #{k}"] = h.delete(k)) if h[k].is_a? Hash }
h

这个例子的灵感来自@muistooshort(akaμ)的工作。

暂无
暂无

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

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