2014-10-02 22 views
1

您好需要更改一个if块内哈希的键值,并在每个循环中为每个键添加一些值我已经完成了它,但它确实有效,但是一直工作随着每次运行而改变并返回不同的结果。更改并编辑一个if块中的哈希键

假设哈希散列叫和我检查它是否有内部的任何散列不是改变其键值

我有它,因为这

... 

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

    ... 

有了这个代码segement第一次运行的回报但随后的运行会混淆起来,并给出很多重复的值,并给出不同的结果。

像滑槽1

 Match User 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 

所以破坏一切 帮助赞赏

+0

请编辑以给出具有两个或三个键值对的散列示例,并显示所需结果的散列。 – 2014-10-02 18:07:48

+0

这看起来很复杂,你可能想问一个更好的方法来解决你的整体问题。 – 2014-10-02 19:28:53

回答

2

假设:

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。)的工作)。

+0

这真棒很好用谢谢! – 2014-10-03 03:06:39

2

您的代码不运行。 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