I read in another answer It's preferred to use array.map(&:dup)
:
Don't use the marshalling trick unless you really want to deep copy an entire object graph. Usually you want to copy the arrays only but not the contained elements.
Would love to see an example illustrating the difference between these two methods.
Besides the syntax it looks to me like they are doing the same thing.
Curious to learn more about the differences between Marshal
and #dup
.
arr = [ [['foo']], ['bar']]
foo = arr.clone
p arr #=> [[["foo"]], ["bar"]]
p foo #=> [[["foo"]], ["bar"]]
foo[0][0] = 42
p arr #=> [[42], ["bar"]]
p foo #=> [[42], ["bar"]]
arr = [ [['foo']], ['bar']]
foo = Marshal.load Marshal.dump arr
p arr #=> [[["foo"]], ["bar"]]
p foo #=> [[["foo"]], ["bar"]]
foo[0][0] = 42
p arr #=> [[["foo"]], ["bar"]]
p foo #=> [[42], ["bar"]]
arr = [ [['foo']], ['bar']]
foo = arr.map(&:dup)
p arr #=> [[["foo"]], ["bar"]]
p foo #=> [[["foo"]], ["bar"]]
foo[0][0] = 42
p arr #=> [[["foo"]], ["bar"]]
p foo #=> [[42], ["bar"]]