From: Chris Shea Date: 2008-08-26T08:10:40+09:00 Subject: Re: Dumb "array of arrays" question On Aug 25, 4:57 pm, RichardOnRails wrote: > Hi, > > I wrote the following intending to create an array of 3 element, each > being itself an array of two elements initialized to zero;  Judging by > "inspect", I seem to have that: > > a = Array.new(3, [0,0]) => [[0, 0], [0, 0], [0, 0]] > > I tried the following,  which confirms that a[0] is indeed a sub- > array. > > a[0].inspect + "; " + a[0].class.to_s => [0, 0]; Array > > Then I tried to assign a number (5) to the first element of the first > sub-array. What I got was more 5's than I bargained for: > > a[0][0]=5 => [[5, 0], [5, 0], [5, 0]] > > What am I missing here? > > Thanks in Advance, > Richard This is a gotcha that trips up everyone the first time they come across it. Array.new(size, obj) creates a new array with _size_ copies of _obj_. That is, your array has three copies of the array [0,0]. Each one is the same as the other. So when you assign to the first element of that array, all copies get updated. You'll want to use Array.new with a block to get different objects: a = Array.new(3, [0,0]) a # => [[0, 0], [0, 0], [0, 0]] a.map {|element| element.object_id} # => [78860, 78860, 78860] a2 = Array.new(3) {[0,0]} a2 # => [[0, 0], [0, 0], [0, 0]] a2.map {|element| element.object_id} # => [77710, 77700, 77690] a2[0][0] = 5 a2 # => [[5, 0], [0, 0], [0, 0]] HTH, Chris