Sergey Beduev
Sergey Beduev

Reputation: 352

Overwriting a hash

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

Answers (2)

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

Dave Newton
Dave Newton

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

Related Questions