From: w_a_x_man Date: 2010-07-15T19:50:39+09:00 Subject: Re: Return nothing when looking outside the bounds of 2D array? On Jul 14, 6:07 pm, w_a_x_man wrote: > On Jul 14, 3:56 pm, Shawn W_ wrote: > > > I have a 2D Array. I have written a method > > Array2D.adjacent(x,y,direction) that returns the adjacent cell to x,y in > > the direction given. How do I deal with the boundary conditions without > > receiving an error message. > > > For example, if I refer to a cell on the top row, and look north there > > will be nothing there, and my program falls over. > > > I will be creating methods that run over the whole 2D array, replacing > > things in random directions, so when it randomly hits a boundary I need > > my program to ignore cells outside the boundary. > > > How can I do this? Thx > > -- > > Posted viahttp://www.ruby-forum.com/. > > Yields nil if out of bounds: > > if ary[y] >   ary[y][x] > else >   nil > end def get2d ary, x, y if ary[y] ary[y][x] else nil end end ary = [ %w(Z Z Z Z), %w(Z H H Z), %w(Z X Z Z) ] puts get2d( ary,2,1 ) puts get2d( ary,1,2 ) puts get2d( ary,3,3 ) puts get2d( ary,4,0 ) --- output --- H X nil nil