簡體   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