1. Deep copy When you copy an object that contains other objects, like an Array, only a reference to these objects is copied. You can see that in action here:
1 2 3 |
food = %w( bread milk orange ) food.map(&:object_id) # [35401044, 35401020, 35400996] food.clone.map(&:object_id) # [35401044, 35401020, 35400996] |
Using the Marshal class, which is normally used for serialization, you can create a ‘deep copy’ of an object.
1 2 3 |
def deep_copy(obj) Marshal.load(Marshal.dump(obj)) end |
The results:
1 |
deep_copy(food).map(&:object_id) # [42975648, 42975624, 42975612] |
2. […]