0

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?

2 Answers 2

3

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
1

Because @var1 and @var2 are references to the same object.

If you want them to maintain separate values you need to copy @@def.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.