How to Create a Multidimensional Array in Ruby

How to Create a Multidimensional Array in Ruby. Though Ruby doesn't provide explicit support for multidimensional arrays, you can implement one yourself if you have a basic knowledge of the language. You must in essence create an "array of arrays" in which each element of the array holds yet another array. To create such a multidimensional array in Ruby, you can write a method used to generate the arrays of arrays so the code doesn't have to be repeated.

Create a Multidimensional Array in Ruby

Step

Write the skeleton of the method. This method will take a number of dimension arguments and return an empty multidimensional array of those dimensions. For example, for a 10x10 array, call this method mda(10,10):def mda(width,height)end

Step

Create an array of width elements.

Step

Create an array of height elements for every element in the array. This makes the "array of arrays" that will be used as a two-dimensional array. To create empty arrays of a specific length, use the Array.new constructor with the length as an argument. Initially, all values in the array will be nil.

Step

Use the map! method as well. The map! method iterates every element in an array, runs a block for every one and assigns the result of the block to the array element. The same result can be achieved using a for loop, but the map! method is more concise: def mda(width,height)a = Array.new(width)a.map! { Array.new(height) }return aend

Step

Use this array with the subscript (square brackets []) operator. For example, if you had a 10x10 array called "a" and wanted the 7,3 element, you would say a[7][3]: a = mda(10,10)# Fill the array with valuesa[7][5] = "a string"a[2][9] = 23# Retrieve valuesputs a[7][5]puts a[2][9]

Step

Take advantage of the ability to "chain" method calls in Ruby. For example, the Array.new method returns an array. You can chain another method call onto that to call a method on the returned array. Since you're chaining the methods, and not using a return statement, you don't need the variable name either:def mda(width,height)Array.new(width).map!{ Array.new(height) }end