From: "Brian Schröder" Date: 2005-05-23T21:29:01+09:00 Subject: Re: a deepcopy for "array = [1,2,3]*5"? On 23/05/05, Boris wrote: > 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]] > > For me [1,2,3]*5 behaves different. irb(main):001:0> [1,2,3]*5 => [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 = Array.new(5) { [1,2,3] } => [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] irb(main):003:0> a[1][1] = 'a' => "a" irb(main):004:0> a => [[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�der -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/