How to Create a Multidimensional Array in Ruby

By Techwalla Internet Editor

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 1

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)

Step 2

Create an array of width elements.

Step 3

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 constructor with the length as an argument. Initially, all values in the array will be nil.

Step 4

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 =! { }
return a

Step 5

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 values
a[7][5] = "a string"
a[2][9] = 23# Retrieve values
puts a[7][5]
puts a[2][9]

Step 6

Take advantage of the ability to "chain" method calls in Ruby. For example, the 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)!{ }

Tips & Warnings

  • Ruby is very expressive. The MDA method can be a short and concise single line of code. Extra lines and keywords only make code look more complicated than it really is.
  • The return statement is not necessary in Ruby. Ruby methods and blocks automatically return the result of the last statement executed in the method or block.