Dissapearing data from array

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.

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

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.
http://github.com/bolthar/freightrain
http://usingimho.wordpress.com

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs