From: David Alan Black Date: 2002-01-25T21:15:58+09:00 Subject: Re: Problem with arrays of arrays (matrices) copying Hello -- On Fri, 25 Jan 2002, jasa wrote: > I have one global matrix '$mat' and I want to reorder the columns > and lines of it. I make a duplicate, twice, in matrix '$temp' and > I reorder the lines and columns from there. > I know the algorithm I use is not optimal, but that is not the issue > B-). > It works OK with reordering lines, but has problems with reordering > columns. > > The problem I report has to do with matrix copying. > It has also to do with the method 'Object.dup'. > I solved the problem, as I will show, but I don't know why. The problem, I think, is that when you dup your matrix, you're getting a shallow dup -- meaning, the actual row objects inside it are the same as the originals, and all you have is a new way to refer to them. Here's a small example where that happens. Note that the id's of t's elements and m's elements are the same: irb(main):002:0> m = [ [1,2,3], [4,5,6] ] [[1, 2, 3], [4, 5, 6]] irb(main):003:0> t = m.dup [[1, 2, 3], [4, 5, 6]] irb(main):004:0> t[0].id 537724350 irb(main):005:0> m[0].id 537724350 Instead of duping, you could do this or something fancier based on this: temp = mat.map {|row| row.dup} # not using globals, hint hint :-) Also, don't forget the Matrix class that comes with the Ruby distribution (though I know that's not the same as working out the problem yourself :-) David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav