Arrays of Arrays: Two-dimensional arrays

Learn about 2D arrays and how they are used in Ruby.

Initializing different types of arrays

We can specify any type while initializing arrays. For example, string:

$ irb
> Array.new(10, 'hello')
=> ["hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello"]

Or Boolean:

Note: Boolean type doesn’t exist in Ruby but, in this course, we intentionally refer to both theTrueClass and FalseClass types as Boolean.

$ irb
> Array.new(10, true)
=> [true, true, true, true, true, true, true, true, true, true]

Or integer:

$ irb
> Array.new(10, 123)
=> [123, 123, 123, 123, 123, 123, 123, 123, 123, 123]

In other words, the element in the array is an arbitrary object. If an element is an object and an array is an object too, we can define an array of arrays:

$ irb
> Array.new(10, [])
 => [[], [], [], [], [], [], [], [], [], []]

If we access this array by index, we’ll reach an array inside the root array. For example, an index with the value of 4 can be used to access the fifth element. Let’s try it in REPL:

$ irb
> arr = Array.new(10, [])
 => [[], [], [], [], [], [], [], [], [], []]
> element = arr[4]
 => []
> element.class
 => Array

Try these commands in the terminal below.

Get hands-on with 1200+ tech skills courses.