2012-10-03 101 views
0

我碰到了奇怪使用散列作为类变量的问题。运行以下代码后,我期望类变量@@class_hash应包含{:one => {'a' => 'one'}, :two => {'a' => 'two'}}类变量越来越重

但是,我运行此代码后,@@class_hash{:one => {'a' => 'two'}, :two => {'a' => 'two'}}

这是为什么?

class Klass 
    @@class_hash = Hash.new({}) 

    def fun1 
    @@class_hash[:one]['a'] = 'one' 
    end 

    def fun2 
    @@class_hash[:two]['a'] = 'two' 
    end 

    def class_hash 
    @@class_hash 
    end 
end 

klass = Klass.new 

klass.fun1 
h1 = klass.class_hash 
raise "h2[:one]['a'] should be 'one', not 'two'" if h1[:one]['a'] == 'two' 
klass.fun2 
h2 = klass.class_hash 
raise "h2[:one]['a'] should be 'one', not 'two'" if h2[:one]['a'] == 'two' 

回答

4

到Hash.new的参数作为默认值,你的情况{}。

每个对未知密钥的访问都使用完全相同的对象(r​​uby并不会奇迹般地为你复制),所以在你的情况下,每个密钥的值都是完全相同的散列。您可以使用块表格完成我认为您想要的操作

Hash.new {|hash, key| hash[key] ={} } 

在这种情况下,将为每个缺失的键使用不同的空散列。