Ruby - Array Multidimensional Arrays

Introduction

To create a multidimensional array, you can create one array and then add other arrays to each of its "slots."

For example, this creates an array containing two elements, each of which is itself an array of two elements:

Demo

a = Array.new(2) 
a[0]= Array.new(2,'hello') 
a[1]= Array.new(2,'world')

You can also create an Array object by passing an array as an argument to the new method.

You can nest arrays inside one another using square brackets.

This creates an array of four arrays, each of which contains four integers:

a = [    [1,2,3,4], 
    [5,6,7,8], 
    [9,10,11,12], 
    [13,14,15,16]  ] 

Here, I have placed the four "subarrays" on separate lines.

The following code starts by creating an array, multiarr, containing two other arrays.

The first of these arrays is at index 0 of multiarr, and the second is at index 1:

multiarr = [['one','two','three','four'],[1,2,3,4]] 

Related Topic