【发布时间】:2012-10-03 22:38:51
【问题描述】:
我遇到了一个使用哈希作为类变量的奇怪问题。运行以下代码后,我希望类变量@@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'
【问题讨论】:
标签: ruby ruby-1.9.2