From: Simon Hicks Date: 2009-09-12T13:49:51+09:00 Subject: Re: Nooby question : multidimensional arrays. --Apple-Mail-63--454131727 Content-Type: text/plain; charset=US-ASCII; format=flowed; delsp=yes Content-Transfer-Encoding: 7bit The first method simply creates an Array of size width and places an Array of size height in each index, so Array.new(2){Array.new(3)} => [ [ nil , nil , nil ] , [ nil , nil , nil] ] The second method is merely a way of accessing a coordinate within the 2d array, so for a = Array2D.new 2, 2 a[0,1] it would first find @data[0] which would return the object in index 0 which is an array [ nil, nil ] and then @data[0][1] would return the object in index 1 of the sub-array which in this case is nil. In fact the logic here is no more complex than the logic for a simple Array... it only looks more complex, because we are using the same method twice... perhaps it'd help to think about it like this def [](x, y) sub_array = @data[x] return sub_array[y] end The third def is exactly the same as the second def, except instead of simply looking to see what's stored at a coordinate, you're changing the object that's stored at that coordinate. Again the logic is the same as with simple arrays, except the object in each index is also an array. I don't know exactly what's causing the error you're seeing, but it looks like you're calling [x,y]= using a value of x that is higher than the maximum index in the outer array, so instead of returning a sub_array it returns nil, and then tries to call [y]= on nil... hth... On 12 Sep 2009, at 11:06, Shawn W_ wrote: > 01 class Array2D > 02 > 03 def initialize(width, height) > 04 @data = Array.new(width) { Array.new(height) } > 05 end > 06 > 07 def [](x, y) > 08 @data[x][y] > 09 end > 10 > 11 def []=(x, y, value) > 12 @data[x][y] = value > 13 end > 14 > 15 end > > Can someone explain what's going on in this code for a newbie. > > I'm getting lost in the looping logic of the second def; and the 3rd > def > I'm guessing has something do do with hashes? > > I'm using this code in a simple 2d array. It was working but then I > changed all of my ranges from (0...value) to (1..value) [I used ranges > to populate my 2D array with hashes] I now get the error message: > > 11:in `[]=': undefined method `[]=' for nil:NilClass (NoMethodError) > -- > Posted via http://www.ruby-forum.com/. > --Apple-Mail-63--454131727--