-
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)
end -
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 Array.new 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 = Array.new(width)
a.map! { Array.new(height) }
return a
end -
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 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













Comments
phox said
on 3/30/2009 map is sort of redundant here:def mda(width, height) return Array.new(width){Array.new(height)}end