Search code examples
rubyhashruby-1.8ruby-enterprise-edition

Hash merging behavior


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?


Solution

  • Yes, instance variable @a_hash and local variable x store the reference to the same Hash instance and when you change this instance (using mutator method merge! that change object in place), these variables will be evaluated to the same value.

    You may want to use merge method that create a copy of the object and don't change original one:

    @a_hash = {:a => 1}
    x = @a_hash
    y = x.merge({:b => 2})
    # y => {:a => 1, :b => 2}
    # x and @a_hash => {:a => 1}