From: Noé Alejandro on
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.
--
Posted via http://www.ruby-forum.com/.

From: Florian Gilcher on

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

> Hi all.
>
> I have the next problem.
>
> a = %w(a b)
> z = %w(1)
> a.insert(1, z)
> puts a
> a
> 1
> 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: Andrea Dallera on
>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 Dallera
http://github.com/bolthar/freightrain
http://usingimho.wordpress.com


On Thu, 2010-04-08 at 02:47 +0900, Noé Alejandro wrote:
> a.insert(1, z)
> puts a


From: Noé Alejandro on
Thanks guys... Florian for your explanation, Andrea for your solution.
Now I understand what happens and how to solve it.

--
Posted via http://www.ruby-forum.com/.