我遇到了一个使用哈希作为类变量的奇怪问题。运行以下代码后,我希望类变量@@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'