From: Shawn W_ Date: 2010-07-16T06:45:46+09:00 Subject: Re: Return nothing when looking outside the bounds of 2D array? Dave Howell wrote: > I was going to suggest using the 'case' statement instead of all those > elsifs, but then I realized there was an even better way. > > class Array2D > > Delta=[[0,0], [0,1], [1,1], [1,0], [1,-1], [0,-1], [-1,-1], [-1,0], > [-1,1]] > attr_reader :width, :height > > def initialize(width, height) > @width = width > @height = height > @data = Array.new(@width) { Array.new(@height) } > end > > def [](x, y, z) > deltaX, deltaY = *Delta[z] > x = x + deltaX % @width > y = y + deltaY > @data[x][y] unless y<0 or y>@height > end > > def []=(x, y, z, value) > deltaX, deltaY = *Delta[z] > x = (x + deltaX) % @width # modulus % allows wrapping > y = y + deltaY > @data[x][y] = value unless y<0 or y>(@height-1) > end > end > > > Obviously the Delta array takes the place of the elsif chains in both [] > and []=. Also, :width and :height are defined with attr_reader, not > attr_accessor, since it doesn't do any good at all to change those > values after the array has been created. Just be aware I'm a complete newb at programing and Ruby, so the more elegant the code, the harder it is for me to read. David, I tried your solution but it still falls over. Don't you need to specify what happens if y<0 or y>(@height-1) is the case? I tried... if y<0 or y>(@height-1) nil else @data[x][y] = value end ...but that didn't work? It falls over the moment it looks north from the top row, or looks south east from the bottom row. Also, I understand the line... deltaX, deltaY = *Delta[z] ...is allocating the Delta array values to the deltaX and deltaY variables based on the direction z given, but what is the * symbol doing? By the way, my program uses a hex grid, not a square grid - I posted a square grid just for clarity. Adjacent cells directions change for odd and even rows on a hex grid, but I think I can just create two Delta arrays (Delta_even and Delta_odd) and modify the 1,0,-1 values for each, then check for odd/eveness in y. I have yet to nut out the other solution but will go through it later today. -- Posted via http://www.ruby-forum.com/.