How to create a multi-dimensional matrix in Ru Ru

Article by Joe Keny

Although it does not provide explicit support for multidimensional arrays, can be applied one yourself if you have a basic knowledge of the language. You must, in essence, creating a "matrix vector" in which each element of the vector has another parent. To create a multi-dimensional matrix in Ruby, you can write a method used to generate arrays of arrays so that the code does not have to be repeated.

Create a multidimensional Array in Ruby Writing the

skeleton of the method. This method will take a series of arguments and return an array dimension vacuum multidimensional those dimensions. For example, to a series 10x10, call this method MDA (10.10): def MDA (width, height) end

Create a set of elements.

Create a wide range of height elements for each element in the matrix. This makes the "whole matrix" that will be used as a two-dimensional array. To create arrays vacuum of a given length, use the builder Array.new with the length as an argument. Initially, all values in the matrix will be zero.

Use the map! and method. The map! iterated method each element in an array, is executed for each block and assigns the result of the block to the parent element. The same result can be achieved using a for loop, but the map! method is more concise: def MDA (width, height) = Array.new (width) a.map! (Array.new (height)) return aend

Use this series with the subscript (in brackets []) operator. For example, if you have an array of 10x10 called "a" and wanted the element 7.3, you would say that [7] [3]: = MDA (10.10) # fill the array with VALUES [7 ] [5] = "a string" [2] [9] = 23 # Recovering a valuesputs [7] [5] puts [2] [9 ]

Take advantage of the ability to "chain" asks Ruby method. For example, the method returns an array Array.new. You can chain another method in which the word to call a method returned to the parent. Since you are chained methods, and not through a declaration of return, it is not necessary the variable name either: def MDA (width, height) Array.new (width). Map! (Array.new (height)) end

This article is written by Writing Articles.

About the Author

Joe Keny - Everthing about internet.The above article can be found in my site internet Articles.

Music video by Kaiser Chiefs performing Ruby. (C) 2006 B-Unique Records Under exclusive license to Polydor Records Ltd. (UK)

Tags: , ,


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply