Is this behavior correct? I'm running some code like the following:
@a_hash = {:a => 1}
x = @a_hash
x.merge!({:b => 2})
At the end of all that, x's value has been changed as expected but so has the value for @a_hash. I'm getting {:a => 1, :b => 2} as the value for both of them. Is this normal behavior in Ruby?
Yes, instance variable
@a_hashand local variablexstore the reference to the sameHashinstance and when you change this instance (using mutator methodmerge!that change object in place), these variables will be evaluated to the same value.You may want to use
mergemethod that create a copy of the object and don't change original one: