From: Todd Benson Date: 2008-08-26T08:23:14+09:00 Subject: Re: Dumb "array of arrays" question On Mon, Aug 25, 2008 at 6:07 PM, Michael Guterl wrote: > On Mon, Aug 25, 2008 at 6:55 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? >> > Use the block form of Array.new > > a = Array.new(3) { [0, 0] } > a[0][0] = 5 There's also... inner_dim = 2 inner_val = 0 outer_dim = 3 a = Array.new(outer_dim) { Array.new(inner_dim, inner_val) } Why would someone do it this way? Because you can change what's inside the new() instead of steadfastly saying it must be [0, 0]. Sort of moving data away from logic a little. Easier to debug, blah, blah... If that's not really a big deal, I would go Michael's and Chris's route. Todd