I want a twodimensional array in Ruby, that I can access for example like this:
if @array[x][y] == "1" then @array[x][y] = "0"
The problem is: I don't know the initial sizes of the array dimensions and i grow the array (with the <<
operator).
How do I declare it as an instance variable, so I get no error like this?
undefined method `[]' for nil:NilClass (NoMethodError)
QUESTION UPDATED:
@array = Array.new {Array.new}
now works for me, so the comment from Matt below is correct!
I just found out the reason why I received the error was because I iterated over the array like this:
for i in 0..@array.length
for j in 0..@array[0].length
@array[i][j] ...
which was obviously wrong and produced the error. It has to be like this:
for i in 0..@array.length-1
for j in 0..@array[0].length-1
@array[i][j] ...