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
Written by Ben Kitzelman
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#