对于ruby中哈希中的每个循环?

时间:2016-01-28 15:19:26

标签: ruby hash

我是红宝石的新人,我学习哈希,我的下面的代码表现得像地狱,请帮助

hash = {"15" => {:a=>"a_15", :b=>"b_15", :c=>"c_15 ", :d=>"Pass"},
        "16" => {:a=>"d_16", :b=>"e_16", :c=>"f_16 ", :d=>"Fail"}}



mod= {}
h = {}
hash.each do |k,v|
  v.each do |x,y|
    mod[x] = y
  end
  h[k] = mod
  # mod={}    # i don't want to use this technique 
              # as its always creates a new object which is not required
end

p h

预期产出:

{"15" => {:a=>"a_15", :b=>"b_15", :c=>"c_15 ", :d=>"Pass"},
 "16" => {:a=>"d_16", :b=>"e_16", :c=>"f_16 ", :d=>"Fail"}}

实际输出:

{"15"=> {:a=>"d_16", :b=>"e_16", :c=>"f_16 ", :d=>"Fail"},
 "16"=> {:a=>"d_16", :b=>"e_16", :c=>"f_16 ", :d=>"Fail"}}

请帮忙!!!! :(

1 个答案:

答案 0 :(得分:3)

在第一次迭代后,你得到了:

h == {"15" => {:a=>"a_15", :b=>"b_15", :c=>"c_15 ", :d=>"Pass"}}

其中值是对mod 的引用。在第二次迭代中,您更改 mod,这显然会更改{em>引用 h['15']的{​​{1}}的值。

快速修复:

mod

以上将生成h[k] = mod.dup 的克隆版本。要检查所描述的行为,您可以运行原始代码,然后执行:

mod

以上将打印the identifiers of the objects,您将看到结果数组的所有键都引用相同的对象。