From: Robert Klemme Date: 2010-07-19T16:43:50+09:00 Subject: Re: Return nothing when looking outside the bounds of 2D array? 2010/7/14 Shawn W_ : > 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 Did anybody suggest modulo operator so far? I only glanced over replies so I might actually have overseen something. Anyway, you can see it working here: irb(main):001:0> a = Array.new(10){|row| Array.new(10) {|col| "#{row},#{col}"}};nil => nil irb(main):002:0> a.size => 10 irb(main):003:0> a[0].size => 10 irb(main):012:0> 15.times {|i| printf "%2d %p %p\n",i,a[0][i % 10],a[i % 10][0]} 0 "0,0" "0,0" 1 "0,1" "1,0" 2 "0,2" "2,0" 3 "0,3" "3,0" 4 "0,4" "4,0" 5 "0,5" "5,0" 6 "0,6" "6,0" 7 "0,7" "7,0" 8 "0,8" "8,0" 9 "0,9" "9,0" 10 "0,0" "0,0" 11 "0,1" "1,0" 12 "0,2" "2,0" 13 "0,3" "3,0" 14 "0,4" "4,0" => 15 Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/