What's the difference between #clone and #dup

171 Views Asked by At

So I've been learning crystal without a ruby background and noticed the api docs have #dup and #clone for basically copying an array.

What exactly is the difference between the two? The api says #dup shallow copies the array whilst #clone deep copies said array. I'm not sure what exactly that entails and which one I should be using.

1

There are 1 best solutions below

0
On BEST ANSWER

#dup will duplicate the array in memory, that is the list of items it contains, but it won't duplicate the items themselves. Mutating the new array won't affect the previous array(e.g. push, pop) but mutating any of its items will affect the item of the previous array since the items are the same objects.

#clone will duplicate the array list in memory, but also its items, by calling #clone recursively. This is a full clone of the original array. Mutating anything, even a deep nested object, won't affect the original content.

Note that this applies to any object, not just arrays, and that the behavior can be customised by overriding the methods in your own objects.

That being said, it only applies for arrays of objects (e.g. class instances). For arrays of primitives (integer, float, struct...) the items will be copied along with the array list by #dup.