Forum: Ruby create copy of array without changing original

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A74096209c78118ff69d50a51129d697?d=identicon&s=25 Jason Lillywhite (jlillywh)
on 2009-01-16 21:07
Why is it that if I create an array, a = [1,2,3]
then do b = a
then b[0] = 99

why is that a[0] magically becomes 99 too?

how can I preserve 'a' after I make a copy of it, then change that new
copy?
A74096209c78118ff69d50a51129d697?d=identicon&s=25 Jason Lillywhite (jlillywh)
on 2009-01-16 21:26
I just found method dup.

So I can do a = [1,2,3]
b = a.dup
b[0] = 99


and then a and be will not be the same.

Thanks.
4d5b5dd4e263d780a5dfe7ac8b8ac98c?d=identicon&s=25 Tim Pease (Guest)
on 2009-01-16 21:33
(Received via mailing list)
On Jan 16, 2009, at 1:06 PM, Jason Lillywhite wrote:

> Why is it that if I create an array, a = [1,2,3]
> then do b = a
> then b[0] = 99
>
> why is that a[0] magically becomes 99 too?
>

a = [1,2,3]
a.object_id    #=> 604244548
b = a
b.object_id    #=> 604244548

Your two variables are referring to the same object ... or another way
of saying that is all variables in ruby hold a reference to an object.
To get a copy of your array ...

b = a.dup
b.object_id    #=> 604262918


Welcome to ruby!

Blessings,
TwP
03ecd36f405282c7b9a8ed1b3955ade4?d=identicon&s=25 Abhi Yerra (Guest)
on 2009-01-16 23:06
(Received via mailing list)
On Sat, Jan 17, 2009 at 05:06:21AM +0900, Jason Lillywhite wrote:
> Why is it that if I create an array, a = [1,2,3]
> then do b = a
> then b[0] = 99
>


> why is that a[0] magically becomes 99 too?
>

b = a points to the same area of memory as a for lists.

> how can I preserve 'a' after I make a copy of it, then change that new
> copy?

b = a.clone

Should copy the list.
This topic is locked and can not be replied to.