From: James Edward Gray II Date: 2006-04-20T02:55:07+09:00 Subject: Re: Probleme with 2-dimensionnal arrays On Apr 19, 2006, at 11:03 AM, Erard Sebastien wrote: > I can't understand why this piece of code doesn't return the array > expected ? > > my_array = Array.new(3, Array(3)) my_array = Array.new(3) { Array.new } > 3.times do |i| > 3.times do [j| > my_array[i][j] = i + j > end > end > > it should return : > [[ 0, 1, 2] [1, 2, 3] [2, 3, 4]] > > but it returns : > [[2, 3, 4] [2, 3, 4] [2, 3, 4]] > > Is my code wrong ? The two argument form of the constructor uses the same object in each slot. Thus, if you change one, all are modified. The block form I used above will be called to generate each object, getting you the desired results. Hope that helps. James Edward Gray II