Dissapearing data from array

  • Thread starter Noé Alejandro
  • Start date
N

Noé Alejandro

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.
 
F

Florian Gilcher

Hi all.
=20
I have the next problem.
=20
a =3D %w(a b)
z =3D %w(1)
a.insert(1, z)
puts a
a
1
b

Try=20

puts a.inspect
#=3D> ["a", ["1"], "b"]
=20
z.clear
puts a
a
b

puts a.inspect
#=3D> ["a", [], "b"]
=20
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=
 
A

Andrea Dallera

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
 
N

Noé Alejandro

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top