I don't understand arrays as objects of a bigger array

In Chris P.'s book, he explains recursion into a bit of detail using
an example in a game he was a part of its making. The explanation he
used was to count the number of tiles there are in a “continent”. I’ll
put the code here and then ask my question after.

These are just to make the map

easier for me to read. “M” is

visually more dense than “o”.

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,o],
[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],
[o,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 world[y][x] != ’ land’

Either it’ s water or we already

counted it, but either way, we don’ t

want to count it now.

 return 0

end

So first we count this tile…

size = 1
world[y][x] = ’ counted land’

…then we count all of the

neighboring eight tiles (and,

of course, their neighbors by

way of the 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

end

puts continent_size(world, 5, 5)

my question: doesn’t world[5][5] mean to compute the whole 5th array of
“world” by the 5th array of “world”, or if we had world[3][8], to
compute
the whole of the 3rd array of “world” by the 8th array of “world”? but
according to this code, the program computes for the actual objects ‘o’
and ‘M’ and not the arrays. aren’t the arrays objects in this case? what
am I missing and what should I know?

read world[5][5] as this:

subarray = world[5]# in this sample [o,o,o,o,M,M,M,M,o,o,o]
object subarray[5]# in this sample M

Hans M. wrote in post #1051895:

read world[5][5] as this:

subarray = world[5]# in this sample [o,o,o,o,M,M,M,M,o,o,o]
object subarray[5]# in this sample M

so then this simply means that [5][5] implies subarray 5 then object
5… right?

Hi,

Actually, this isn’t even a special syntax. It’s just two subsequent
method calls:

(world[5])[5]

You call the [] method on world. This returns the 6th element von world,
which is an array. And on this array you again call the [] method.

It works exactly like any other method chain:

str = “abc”
puts str.reverse.upcase

not realy its subarray 6 because there is beginning with 0

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs