Why is variable constant assigned

Why when I assign a constant to a variable and update it, the constant is updated to? Is the behavior or error expected?

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"} 

      

+3


source to share


2 answers


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

  • Constant A

  • Variable b

  • Hash { :test => '123' }



The first two represent both kinds of variables. The third is the object. The difference between variables and objects is critical. Variables only refer to objects. When you assign the same object to two variables, they both refer to the same object. Only one object was created, so when it changes, both variables refer to the changed object.

+8


source


This is due to the shallow copy mechanism. In your example, A and b are actually references to the same object. To avoid using:

b = A.dup

      



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

For more information see here what a shallow and deep copy.

+3


source







All Articles