Deep and Shallow copy in Rails

Shallow Copy: They don’t copy the objects that might be referenced within the copied object.In rails dup and clone are used for this.

Deep Copy: All the objects are copied.In rails deep_dup and deep_clone are used for this.

Shallow Copy:

a = {1 => [2,3,4]}
b = a.dup
a[1]<< 5
a
# => {1=>[2, 3, 4, 5]} 
b
# => {1=>[2, 3, 4, 5]} 

a[1].object_id
# => 70283040856600 
b[1].object_id
# => 70283040856600

Deep Copy:

a1= {1 => [2,3,4]} 
b1 = a1.deep_dup
a1[1]<< 5
b1
# => {1=>[2, 3, 4]} 
a1
# => {1=>[2, 3, 4, 5]} 

a1[1].object_id
# => 70283036017040 
b1[1].object_id
# => 70283036034520 

clone does two things that dup doesn’t:

1. Copy the singleton class of the copied object

#shallow copy
a = Object.new
def a.foo; :foo end
p a.foo
# => :foo
b = a.dup
p b.foo
# => undefined method `foo' for #<Object:0x007f8bc395ff00> (NoMethodError) vs clone:
#deep copy
a = Object.new
def a.foo; :foo end
p a.foo
# => :foo
b = a.clone
p b.foo
# => :foo

2. Maintain the frozen status of the copied object

a = Object.new
a.freeze
p a.frozen?
# => true

b = a.dup
p b.frozen?
# => false

c = a.clone
p c.frozen?
# => true
comments powered by Disqus