How can I copy an array and its elements? (call by value)

J

Janus Bor

Hi all,

I'm failing at something really basic: copying an array and its
contents, so that I can modify the copy without modifying the original.

Here's an example:

irb(main):006:0> a = [1, 2]
=> [1, 2]
irb(main):007:0> b = a
=> [1, 2]
irb(main):008:0> b.delete(1)
=> 1
irb(main):009:0> b
=> [2]
irb(main):010:0> a
=> [2]

I guess the problem is that arrays are called by name not by value, so
that 'b' copy points to the same adress in memory as 'a'. How can I
create an independent copy of 'a'?

Thanks,
Janus
 
F

Fleck Jean-Julien

Hello,
I'm failing at something really basic: copying an array and its
contents, so that I can modify the copy without modifying the original.

I think the method 'dup' is what you are looking for

irb(main):001:0> a =3D [1,2]
=3D> [1, 2]
irb(main):002:0> b =3D a.dup
=3D> [1, 2]
irb(main):003:0> b.delete(1)
=3D> 1
irb(main):004:0> b
=3D> [2]
irb(main):005:0> a
=3D> [1, 2]

Cheers,

--=20
JJ Fleck
PCSI1 Lyc=E9e Kleber
 
R

Robert Klemme

Thank you both, that's exactly what I'm looking for!

Just note that #dup and #clone do a shallow copy, so if you modify
objects in the copy this change will also be seen via the original
Array. Depending on what you do #map might be more appropriate.

Kind regards

robert
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top