On Jul 14, 6:07=A0pm, w_a_x_man <w_a_x_... / yahoo.com> wrote:
> On Jul 14, 3:56=A0pm, Shawn W_ <sha... / internode.on.net> wrote:
>
> > I have a 2D Array. I have written a method
> > Array2D.adjacent(x,y,direction) that returns the adjacent cell to x,y i=
n
> > 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]
> =A0 ary[y][x]
> else
> =A0 nil
> end

def get2d ary, x, y
  if ary[y]
    ary[y][x]
  else
    nil
  end
end

ary =3D [
  %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