Last Updated: February 25, 2016
·
434
· benkitzelman

Dup / clone is shallow

I was surprised that in ruby dup on a hash creates a shallow copy

a = {one: {two: {val: 'initial'}}}
b = a.dup
b[:one][:two][:val] = 'modified'
a == b         # -> true

Marshalling ensures a deep copy

a = {one: {two: {val: 'initial'}}}
b = Marshal.load(Marshal.dump(a))
b[:one][:two][:val] = 'modified'
a == b         # -> false