From: Dave Howell Date: 2010-07-15T18:23:00+09:00 Subject: Re: Return nothing when looking outside the bounds of 2D array? 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.