# Dissapearing data from array

**URL:** <https://www.ruby-forum.com/t/dissapearing-data-from-array/186483>\
**Category:** Ruby\
**Created:** [April 7, 2010, 7:47pm UTC](https://www.ruby-forum.com/t/dissapearing-data-from-array/186483 "2010-04-07T19:47:34Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![nax](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f07891/32.png) [@nax](https://www.ruby-forum.com/u/nax)\
**Post date:** [April 7, 2010, 7:47pm UTC](https://www.ruby-forum.com/t/dissapearing-data-from-array/186483/1 "2010-04-07T19:47:34Z")

</div>

Hi all.

I have the next problem.

a = %w(a b)  
z = %w(1)  
a.insert(1, z)  
puts a  
a  
1  
b

z.clear  
puts a  
a  
b

Oopss… where “1” is? what happened? what can I do to keep “1” when I  
clear the array (z)?

Thanks a lot.

---

<div class="post-metadata">

**Author:** ![nax](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f07891/32.png) [@nax](https://www.ruby-forum.com/u/nax)\
**Post date:** [April 7, 2010, 8:02pm UTC](https://www.ruby-forum.com/t/dissapearing-data-from-array/186483/2 "2010-04-07T20:02:30Z")

</div>

On Apr 7, 2010, at 7:47 PM, Noé Alejandro wrote:

> b  
> Try

puts a.inspect  
#=\> [“a”, [“1”], “b”]

> z.clear  
> puts a  
> a  
> b

puts a.inspect  
#=\> [“a”, [], “b”]

> Oopss… where “1” is? what happened? what can I do to keep “1” when I  
> clear the array (z)?

Ruby uses references. So a.insert(1, z) inserts a reference to z at  
position 1 in the array. So once you clear z, it will be cleared  
noticed by everyone referring to it - a, in this case.

Regards,  
Florian

---

<div class="post-metadata">

**Author:** ![nax](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f07891/32.png) [@nax](https://www.ruby-forum.com/u/nax)\
**Post date:** [April 7, 2010, 8:03pm UTC](https://www.ruby-forum.com/t/dissapearing-data-from-array/186483/3 "2010-04-07T20:03:05Z")

</div>

> From what i’ve understood your aim is to “detach” the reference of the  
> inserted element from the original one. That can be done with z.clone,  
> in your example it will look like this:

a = %w(a b)  
z = %w(1)  
a.insert(1, z.clone)  
z.clear  
puts a  
a  
1  
b

–  
Andrea D.

> **[GitHub - bolthar/freightrain: Ruby desktop development made easy](https://github.com/bolthar/freightrain)**
>
> Ruby desktop development made easy. Contribute to bolthar/freightrain development by creating an account on GitHub.

> **[using (IMHO)](https://usingimho.wordpress.com)**
>
> Andrea Dallera 's blog

---

<div class="post-metadata">

**Author:** ![nax](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f07891/32.png) [@nax](https://www.ruby-forum.com/u/nax)\
**Post date:** [April 7, 2010, 8:33pm UTC](https://www.ruby-forum.com/t/dissapearing-data-from-array/186483/4 "2010-04-07T20:33:50Z")

</div>

Thanks guys… Florian for your explanation, Andrea for your solution.  
Now I understand what happens and how to solve it.
