0

I'm trying to update a multidimensinal hash and then compare the new hash with the old one, but no matter what value I change they still show up as equal. Is there an efficient way to compare every value in two hashes and return false if one isn't true

hash1 = {foo: {bar: "baz"}}
hash2 = hash1
hash2[:foo][:bar] = "foz"
hash2 == hash1 # This should be false but is returning true

1 Answers1

0

Unlike assigning to simple primitive objects like integers, when you assign a variable to a hash, it will point to the same hash object. So, hash2 is pointing on the same object as hash1 in memory. If you need them to be structurally the same but are different objects, you need to copy the first hash deeply.

def deep_copy(hash)
  Marshal.load(Marshal.dump(hash))
end

hash1 = {foo: {bar: "baz"}}
hash2 = deep_copy(hash1)
hash2[:foo][:bar] = "foz"
hash2 == hash1
Adrian
  • 425
  • 4
  • 13