Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 40 / 68

Shallow Copy vs. Deep Copy

In this lesson you will learn the difference between a shallow and a deep copy in Ruby so you can avoid surprising bugs when duplicating objects. This is for anyone searching for "Ruby dup clone how to use".

A shallow copy (.dup) duplicates only the outermost container; any nested objects inside remain shared with the original. A deep copy duplicates everything inside as well, so changing the copy leaves the original untouched.

The sample code shallow-copies the hash original with .dup and then changes the nested part (address[:city]) on the copy - and original changes too. For the deep copy it goes via JSON.

A common stumbling block for beginners is that .dup alone does not duplicate the nested structure. This is the classic cause of the bug where "I copied it, but the original changed too".

When you need a deep copy, Marshal and JSON both work and you pick to suit the job. The more state an application manages, the more this difference matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)