How to properly initialize a 2D array in Ruby
I am working on a small game and that game happens to have a two dimensional map. In trying to be minimalistic, the implementation of the map is just a 2d array. For some reason, I decided it was a good idea to learn a new programming language and 2 new frameworks to make this game.
When creating an array in Ruby, one can prefill it easily like so
myarray = Array(10, 0)
So without reading any documentation I thought “well I think I know what I’m doing” and proceeded to write
myarray = Array.new(10, Array.new(10, 0))
The problem here is that it makes an array of 10 references to the same array. The right way to do it is to use a block following a call to Array with only 1 argument. This is conveniently listed fairly early on in the Ruby Array documentation.
myarray = Array.new(10) { Array.new(10, 0) }
Its just one of those things that happens when you are learning a new language.