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"}
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:
The constant
AThe variable
bThe 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.