a deepcopy for "array = [1,2,3]*5"?

B

Boris

Been looking this up in the myriad of deepcopy strands, but couldn't
find it in 30 minutes, so I'm posting the question.

The question is simple. What way would you create an array that
contains 5 copies of an array, without the copies interfering with each
other?

array = [1,2,3]*5

generates:
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

but unfortunately also makes 'array[1][1] = "a"' change it like this:

[[1,"a",3],[1,"a",3],[1,"a",3],[1,"a",3],[1,"a",3]]

---------
Anyway, found a solution during tinkering, although I don't know why.
Thought I'd just still post it anyway.

ar = []
5.times{ar << [1,2,3]}

works, and 'array[1][1] = "a"' results in the thing I want

[[1,2,3],[1,"a",3],[1,2,3],[1,2,3],[1,2,3]]
 
F

Florian Frank

The question is simple. What way would you create an array that
contains 5 copies of an array, without the copies interfering with each
other?

array = Array.new(5) { [1,2,3] }
 
B

Brian Schröder

Been looking this up in the myriad of deepcopy strands, but couldn't
find it in 30 minutes, so I'm posting the question.
=20
The question is simple. What way would you create an array that
contains 5 copies of an array, without the copies interfering with each
other?
=20
array =3D [1,2,3]*5
=20
generates:
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
=20
but unfortunately also makes 'array[1][1] =3D "a"' change it like this:
=20
[[1,"a",3],[1,"a",3],[1,"a",3],[1,"a",3],[1,"a",3]]
=20
---------
Anyway, found a solution during tinkering, although I don't know why.
Thought I'd just still post it anyway.
=20
ar =3D []
5.times{ar << [1,2,3]}
=20
works, and 'array[1][1] =3D "a"' results in the thing I want
=20
[[1,2,3],[1,"a",3],[1,2,3],[1,2,3],[1,2,3]]
=20
=20

For me [1,2,3]*5 behaves different.

irb(main):001:0> [1,2,3]*5
=3D> [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]


For what you want you could use:

irb(main):002:0> a =3D Array.new(5) { [1,2,3] }
=3D> [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
irb(main):003:0> a[1][1] =3D 'a'
=3D> "a"
irb(main):004:0> a
=3D> [[1, 2, 3], [1, "a", 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

$ ruby -v
ruby 1.8.2 (2005-04-11) [i386-linux]

Which version of ruby are you using?

best regards,

Brian Schr=F6der

--=20
http://ruby.brian-schroeder.de/

Stringed instrument chords: http://chordlist.brian-schroeder.de/
 
P

Premshree Pillai

For me [1,2,3]*5 behaves different.
=20
irb(main):001:0> [1,2,3]*5
=3D> [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

He prolly meant [[1, 2, 3]]*5

--=20
Premshree Pillai
 

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
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top