# Shadow copy and deep copy

**URL:** <https://rubytalk.org/t/shadow-copy-and-deep-copy/60776>\
**Category:** ruby-talk\
**Created:** [9 November 2010 08:24 UTC](https://rubytalk.org/t/shadow-copy-and-deep-copy/60776 "2010-11-09T08:24:57Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Eva](https://avatars.discourse-cdn.com/v4/letter/e/dbc845/32.png) [@Eva](https://rubytalk.org/u/Eva)\
**Post date:** [9 November 2010 08:24 UTC](https://rubytalk.org/t/shadow-copy-and-deep-copy/60776/1 "2010-11-09T08:24:57Z")

</div>

Hello,

x=[1,2,3]  
y=x.dup

this is a shadow copy, I know the theory behind it.

z=x

is this a deep copy? (z is the deep copy of x?)

Thanks

---

<div class="post-metadata">

**Author:** ![Adrian\_Tepes](https://avatars.discourse-cdn.com/v4/letter/a/7ba0ec/32.png) [@Adrian\_Tepes](https://rubytalk.org/u/Adrian_Tepes)\
**Post date:** [9 November 2010 09:29 UTC](https://rubytalk.org/t/shadow-copy-and-deep-copy/60776/2 "2010-11-09T09:29:08Z")

</div>

Eva wrote in post #960269:

> Hello,
> 
> x=[1,2,3]  
> y=x.dup
> 
> this is a shadow copy, I know the theory behind it.
> 
> z=x
> 
> is this a deep copy? (z is the deep copy of x?)
> 
> Thanks

I don't think it's deep copy.  
irb(main):010:0\> print z.\_\_id\_\_  
137429210=\> nil  
irb(main):011:0\> print x.\_\_id\_\_  
137429210=\> nil  
irb(main):012:0\> print y.\_\_id\_\_  
137515980=\> nil  
irb(main):013:0\> z.push 4  
=\> [1, 2, 3, 4]  
irb(main):014:0\> p x  
[1, 2, 3, 4]  
=\> [1, 2, 3, 4]

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Robert\_K1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/robert_k1/32/1830_2.png) [@Robert\_K1](https://rubytalk.org/u/Robert_K1)\
**Post date:** [9 November 2010 13:41 UTC](https://rubytalk.org/t/shadow-copy-and-deep-copy/60776/3 "2010-11-09T13:41:27Z")

</div>

> x=[1,2,3]  
> y=x.dup
> 
> this is a shadow copy, I know the theory behind it.

Actually it's called "shallow copy". And what #dup really does  
depends on the class so it could even implement a deep copy (although  
that is normally not the case). In the case of Array you are correct,  
it's a shallow copy.

> z=x
> 
> is this a deep copy? (z is the deep copy of x?)

No, there is no copy of state at all. This is called "aliasing": now  
both z and x point to the same object.

Example for deep copy:

z = Marshal.load(Marshal.dump(x))

Kind regards

robert

> **···**
>
> 2010/11/9 Eva \<eva54321@sina.com\>:
> 
> --  
> remember.guy do |as, often| as.you\_can - without end  
> [http://blog.rubybestpractices.com/](http://blog.rubybestpractices.com/)
