为什么 ruby 会覆盖类实例变量@var1
?
require 'pp'
class Foo
@@def = { :key1 => "someval1", :key2 => "someval2" }
def initialize
@var1 = @var2 = @@def
@var1[:key1] = "newval1"
@var2[:key1] = "newval2"
pp(@var1)
pp(@var2)
end
end
f = Foo.new
输出
{:key1=>"newval2", :key2=>"someval2"}
{:key1=>"newval2", :key2=>"someval2"}
请说出为什么会这样。我怎样才能避免这种情况?