# Content of an array gets cleared

**URL:** <https://www.ruby-forum.com/t/content-of-an-array-gets-cleared/150130>\
**Category:** Ruby\
**Created:** [October 4, 2008, 5:54am UTC](https://www.ruby-forum.com/t/content-of-an-array-gets-cleared/150130 "2008-10-04T05:54:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![parvg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bbe5ce/32.png) [@parvg](https://www.ruby-forum.com/u/parvg)\
**Post date:** [October 4, 2008, 5:54am UTC](https://www.ruby-forum.com/t/content-of-an-array-gets-cleared/150130/1 "2008-10-04T05:54:13Z")

</div>

Hello,

Looking for you suggestions.

1. array = %w(a b c d e)
2. tempArray = array
3. array.clear
4. puts tempArray.length

line 4 outputs: 0  
Why does my tempArray get cleared also?  
Any suggestions on how to keep the tempArray content from clearing out?

Thanks

---

<div class="post-metadata">

**Author:** ![parvg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bbe5ce/32.png) [@parvg](https://www.ruby-forum.com/u/parvg)\
**Post date:** [October 4, 2008, 6:07am UTC](https://www.ruby-forum.com/t/content-of-an-array-gets-cleared/150130/2 "2008-10-04T06:07:20Z")

</div>

Parv G. wrote:

> Hello,
> 
> Looking for you suggestions.
> 
> 1. array = %w(a b c d e)
> 2. tempArray = array
> 3. array.clear
> 4. puts tempArray.length
> 
> line 4 outputs: 0  
> Why does my tempArray get cleared also?  
> Any suggestions on how to keep the tempArray content from clearing out?
> 
> Thanks

because array and tempArray are references to the same Array instance.

# see same object

array.object\_id #=\> -605829518  
tempArray.object\_id #=\> -605829518

tempArray = array.dup #=\> make a shallow copy.  
array.clear  
puts tempArray.length #=\> 5

---

<div class="post-metadata">

**Author:** ![parvg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bbe5ce/32.png) [@parvg](https://www.ruby-forum.com/u/parvg)\
**Post date:** [October 4, 2008, 6:16am UTC](https://www.ruby-forum.com/t/content-of-an-array-gets-cleared/150130/3 "2008-10-04T06:16:38Z")

</div>

> tempArray = array.dup #=\> make a shallow copy.  
> array.clear  
> puts tempArray.length #=\> 5

That should do the trick for me.

Thanks a lot!  
Parv
