p0deje
p0deje

Reputation: 4053

Why assigned to variable constant is updated

Why when I assign constant to variable and update it, constant is being updated to? Is it expected behavior or bug?

ruby-1.9.3-p0 :001 > A = { :test => '123' }
 => {:test=>"123"} 
ruby-1.9.3-p0 :002 > b = A
 => {:test=>"123"} 
ruby-1.9.3-p0 :003 > b[:test] = '456'
 => "456" 
ruby-1.9.3-p0 :004 > A
 => {:test=>"456"} 

Upvotes: 3

Views: 604

Answers (2)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

This is because of the shallow copy mechanism. In your example A and b are actually references to the same object. To avoid that use:

b = A.dup

This will initialize b with a copy of A instead of pointing it to the same hash(i.e. this uses deep copy).

For more info see here what shallow and deep copy is.

Upvotes: 3

Chuck
Chuck

Reputation: 237010

This is expected behavior, but why isn't always obvious. This is a very important distinction in languages like Ruby. There are three things in play here:

  1. The constant A

  2. The variable b

  3. The hash { :test => '123' }

The first two are both kinds of variables. The third is an object. The difference between variables and objects is crucial. Variables just refer to objects. When you assign the same object to two variables, they both refer to the same object. There was only ever one object created, so when you change it, both variables refer to the changed object.

Upvotes: 7

Related Questions