From: Shawn W_ Date: 2010-07-15T10:04:30+09:00 Subject: Re: Return nothing when looking outside the bounds of 2D array? Thx. Don't quite understand that code. I tried plugging in some nils but didn't work. Do I just need to assign nil values to the cells outside the bounds of my array for the program to ignore them? Here's what I've got so far. At the moment everything is wrapping. I need it to wrap left and right, but to be capped top and bottom. class Array2D attr_accessor :width, :height def initialize(width, height) @width = width @height = height @data = Array.new(@width) { Array.new(@height) } end # Returns adjacent cell of given 2D array index x,y, in the given direction z, where z = 0 is no direction (the cell in the middle), and z = 1-8 are the surrounding cells. def [](x, y, z) x = x % @width # modulus % allows wrapping y = y % @height if z == 0 @data[x][y] elsif z == 1 @data[x][y+1] elsif z == 2 @data[x+1][y+1] elsif z == 3 @data[x+1][y] elsif z == 4 @data[x+1][y-1] elsif z == 5 @data[x][y-1] elsif z == 6 @data[x-1][y-1] elsif z == 7 @data[x-1][y] elsif z == 8 @data[x-1][y+1] end end # Allows the allocation of values to adjacent cell of given 2D array index x,y, in the given direction z, where z = 0 is no direction (the cell in the middle), and z = 1-8 are the surrounding cells. def []=(x, y, z, value) x = x % @width # modulus % allows wrapping y = y % @height if z == 0 @data[x][y] = value elsif z == 1 @data[x][y+1] = value elsif z == 2 @data[x+1][y+1] = value elsif z == 3 @data[x+1][y] = value elsif z == 4 @data[x+1][y-1] = value elsif z == 5 @data[x][y-1] = value elsif z == 6 @data[x-1][y-1] = value elsif z == 7 @data[x-1][y] = value elsif z == 8 @data[x-1][y+1] = value end end end # This method replaces contents of 9 cells in a square configuration at a random location on the 2D array. def form_plates x = rand(@cols) y = rand(@rows) Array2D[x,y,0] = "X " Array2D[x,y,1] = "X " Array2D[x,y,2] = "X " Array2D[x,y,3] = "X " Array2D[x,y,4] = "X " Array2D[x,y,5] = "X " Array2D[x,y,6] = "X " Array2D[x,y,7] = "X " Array2D[x,y,8] = "X " end -- Posted via http://www.ruby-forum.com/.