hey all,
this is a great community and I’m glad I found it…also, this is my
first post.
In the code example below taken from Chris P. Learn to Program RoR
book, I’m curious why there is (what looks like to me) a hanging
variable: “size”. It is the third line from the bottom. I understand
how recursion is working here, but I’m not sure why “size” is just
sitting there at the bottom. I removed the line and re-ran the program
and still got the correct result. Am I missing something?
–
M = ’ land ’
o = ’ water ’
world = [[o,o,o,o,o,o,o,o,o,o,o],
[o,o,o,o,M,M,o,o,o,o,o],
[o,o,o,o,o,o,o,o,M,M,M],
[o,o,o,M,o,o,o,o,o,M,o],
[o,o,o,M,o,M,M,o,o,o,o],
[o,o,o,o,M,M,M,M,o,o,o],
[o,o,o,M,M,M,M,M,M,M,o],
[o,o,o,M,M,o,M,M,M,o,o],
[o,o,o,o,o,o,M,M,o,o,o],
[M,M,o,o,o,M,o,o,o,o,o],
[o,o,o,o,o,o,o,o,o,o,o]]
def continent_size world, x, y
if x > 10 && y > 10
size = 0
else
if world[y][x] != ’ land ’
return 0
end
end
size = 1
world[y][x] = ’ counted land ’
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
#THIS LAST “SIZE” IS WHAT I’M TALKING ABOUT ABOVE. YOU CAN REMOVE IT
AND THE #PROG STILL RUNS CORRECTLY
end
puts continent_size(world, 5, 5)
Thanks in advance for any thoughts you have.
Best,
Jordan