Reputation: 352
Why does ruby overwrite class instance variable @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
Output
{:key1=>"newval2", :key2=>"someval2"}
{:key1=>"newval2", :key2=>"someval2"}
Please say why this happened. And how can I avoid that?
Upvotes: 0
Views: 152
Reputation: 717
It happens because you set both of the variables to point to the same hash. Editing one would edit all 3 variables (including @@def) because it's all the same hash.
The easiest way to to avoid this is to clone
the hash.
@var2 = @@def.clone
@var1 = @@def.clone
Upvotes: 3
Reputation: 160261
Because @var1
and @var2
are references to the same object.
If you want them to maintain separate values you need to copy @@def
.
Upvotes: 1