Use loop counter for 2D array index

The code, data = Array[[],[]]
… actually creates an array with only two starting members, that are empty array objects.

This means they have members [0] and [1], and everything was fine the first two times through your loop.

The third time through, however when you were calling data[2] the Array#[] method returned nil because an index beyond the member range was passed. And the second subscript (index) call of [0]= is really a call of nil[0]=, which causes the NoMethodError, because the NilClass does not have a method named “[]=”.

It’s a quirk of Ruby that nil gets returned in cases like this, because index methods double as existence query methods. It’s as if you are asking first IF member 2 of data exits, return it otherwise return nil. In Ruby it is customary to test return values for “nilness” or boolean true, as nil gets logically evaluated as FALSE. (You will see this also in IO methods, where 'nil is returned if the user cancels, or a file object does not exist.)
So after calling such methods, you do a boolean test before using the return value…

value = data[i]
if value
  # use value
else
  # recover gracefully, exit method, etc.
end

You can initialize an array with n number of nested empty arrays thus:

data = Array::new(n) {|i| Array::new }

(In this case, the index i is unused inside the block.)


Second your original loop would have had 751 iterations. You do not really have to use a max counter like that.

In Ruby can just do:

for counter in data_array
  # code
end

… and it will only iterate what members actually exist in the array.
It is similar to

data_array.each do |counter|
  # code
end

The for loop is slightly faster, as it does not create a new variable scope with every iteration. The each method does create a new scope.


As a newb, you may not realize that the Enumerable mixin module, is mixed into the Array and Hash classes, (as well as most of the SketchUp API’s collection classes.) This mixin library adds many useful iteration and query methods.


Good primer docs are listed here:
Index of Files, Classes & Methods in Ruby 2.7.2 (Ruby 2.7.2)
You can ignore the few at the top, beginning with “.lib” and “.test”.
Read the one on globals, then skip all the Rake docs.
Start again with the “re.rdoc” and down to the end of the list.

3 Likes