create copy of array without changing original

J

Jason Lillywhite

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?
 
J

Jason Lillywhite

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

Tim Pease

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
 
A

Abhi Yerra

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.
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top