Take the 2-minute tour ×

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"} 
share|improve this question
Note that this also shows that "constants" in Ruby are not actually enforced to be constant. –  Andrew Marshall Apr 10 '12 at 7:12
possible duplicate of Constant Assignment Bug in Ruby? –  Andrew Grimm Apr 10 '12 at 7:25
add comment

2 Answers

up vote 6 down vote accepted

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.

share|improve this answer
+1 for mentioning references vs. data ("objects"). –  Andrew Marshall Apr 10 '12 at 7:13
add comment

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.

share|improve this answer
Thanks! That's what I wanted to know. –  p0deje Apr 10 '12 at 6:00
It's probably not good that this answer doesn't mention references at all. –  Andrew Marshall Apr 10 '12 at 7:12
Point taken. Thank you. –  Ivaylo Strandjev Apr 10 '12 at 7:19
add comment

Your Answer


