On Fri, Jul 16, 2010 at 11:11 AM, Shawn W_ <shawnw / internode.on.net> wrote:
> Okay, just found out that...
>
> @data[x][y] unless y<0 or y>@height
>
> ...is the same as stating nil anyway, according to
> http://www.themomorohoax.com/2009/05/21/when-to-use-nil-in-ruby-methods
>
> The error I'm getting is...
>
> undefined method `[]=' for nil:NilClass (NoMethodError)
>
> ...when the program hits this part of the code...
>
> Array2D[x,y,1] = "X "

The basic problem is that ruby doesn't have rectangular arrays, you
have to use arrays of arrays. So "array[y][x]" means "get array[y]
(which is itself an array) and take the xth element of that". So let's
say you initialize your array to [4][3]. Then you have

array = [
[nil, nil, nil],  # array[0]
[nil, nil, nil],  # array[1]
[nil, nil, nil],  # array[2]
[nil, nil, nil]   # array[3]
]

Now say you set array[1][2] = "X". Your new array is

array = [
[nil, nil, nil],  # array[0]
[nil, nil,  X ],  # array[1]
[nil, nil, nil],  # array[2]
[nil, nil, nil]   # array[3]
]

you can do this either via

array[1][2] = "X"

or

a = array[1]
a[2] = "X"

So what happens when you go off the end of the array? Calling array[n]
where n is out of bounds will return nil, as expected...

array[1][100] # => nil

which is equivalent to

a = array[1] #=> [..., ..., ...]
a[100] #=> nil

But if you go out of bounds in the other dimension

array[100][1] # => undefined method `[]=' for nil:NilClass (NoMethodError)

because what you're in effect doing is

a = array[100] #=> nil
a[1] # => trying to call [] on nil, which raises the error

martin