I have a two-dimensional array created like this:
array = Array.new(10){Array.new(10)}
How can I assign default values for each cell on initialization?
I know I can do it with two nested each
loops but I wondered if there is another way?
I have a two-dimensional array created like this:
array = Array.new(10){Array.new(10)}
How can I assign default values for each cell on initialization?
I know I can do it with two nested each
loops but I wondered if there is another way?
Two-dimensional array
To make your two-dimensional array, you can just do what kiddorails said:
Or you could do it this way:
Bad two-dimensional array
While the following code is tempting (two people have tried to use it to answer this question) it is NOT the right way to make a two-dimensional array:
This actually creates a single array with 10 zeroes, which is fine, but then it creates another array which just holds ten references to that array. The code above only creates two arrays!
Hash that acts like a two-dimensional array
Another more Ruby-like way to implement this data structure would be to use a hash and use x,y coordinate pairs as the keys. This is nice because it makes a location in the 2D array be a first-class object that you can easily pass around without having to worry about how exactly that location is represented. It becomes easier to iterate through every spot because you don't have to have nested loops, and that means it will probably be easier to duplicate the data. Also, Ruby's hash structure has a feature for letting you set a default value, so you don't have to do any tricky work to initialize the data.
Here is some example code showing the idea:
You can also use your own custom-designed object for the hash keys if you want:
Whatever you do, be careful to not modify any object you are using as a hash key, or else you will accidentally be modifying the data in the hash and actually screwing up the internal structure of the hash, requiring a rehash.
Just supply a second argument with the value:
Here, the default value is
4
and thus, a 10*10 2D array is created with default value of4
.