From: Mariano Kamp Date: 2006-10-10T15:41:49+09:00 Subject: Re: Learn to Program, by Chris Pine Hi Mike, what your guard should do is prevent the recursion go across the boundaries of your world, right? I would put the guard at the beginning of the method to make sure that the rest of the method can be sure of handling valid data. if x < 0 || x > 10 || y < 0 || y > 10 return 0 # respect the world's boundaries end > def continent_size world, x, y > if world[y][x] != 'land' > # either it's water or we've already counted it; we don't want to > count it > # again > return 0 > end That's a bit of a problem as your code might already call with out of bounds coordinates. Put the boundary guard (see above) before that. > if ((y <= 10 && y > 0) && (x <= 10 && x > 0)) An array starts to count at zero ... so it needs to be (y <= 10 && y >= 0), right? You have eleven columns and eleven rows. So the array indices are 0..10. > # So, first we count this tile... > size = 1 > world[y][x] = 'counted land' > > > # ...then we count all of the > # neighboring eigth tiles (and, > # of course, their neighbors via recursion) > size = size + continent_size(world, x-1, y-1) > size = size + continent_size(world, x , y-1) > size = size + continent_size(world, x+1, y-1) > size = size + continent_size(world, x-1, y ) > size = size + continent_size(world, x+1, y ) > size = size + continent_size(world, x-1, y+1) > size = size + continent_size(world, x , y+1) > size = size + continent_size(world, x+1, y+1) > size Ok, you're returning the size here, but > end what are you returning here, if you haven't been in this if-block? nil. That is a major part of your problem... > end Use the code above and put it after the definition of the method. Remove your own "if" and your method should work. > puts continent_size(world, 5, 5) #this should be fine; but what about > (11,11)? That's up to you. In my code (the guard) it returns 0. So that 11,11 will return 0. You could also raise an exception that the coordinates are out-of- bounds, but I guess that will come later in your book and is not that straight forward applicable here. Cheers, Mariano