Topic Overview

Welcome to today's session on "Multidimensional Arrays and Their Traversal in Ruby". Multidimensional arrays are types of arrays that store arrays at each index instead of single elements. Picture it as an 'apartment building' with floors (the outer array) and apartments on each floor (the inner array). Our goal today is to strengthen your foundational knowledge of these 'apartment buildings' and how to handle them effectively in Ruby.

Creating Multidimensional Arrays

To construct a multidimensional or nested array in Ruby, we use arrays inside arrays. Here's an example of a 2-dimensional array:

# Creating a 2D array
array = [[1, 2, 3], 
         [4, 5, 6], 
         [7, 8, 9]]
puts array.inspect

In this example, array is a 2-dimensional array, just like a 3-story 'apartment building,' where every floor is an inner array.

Indexing in Multidimensional Arrays

All indices in Ruby arrays are 0-based. Let's say you want to visit an apartment on the second floor (index 1) and bring a package to the first unit (index 0) in this building. Here's how you can do it:

# Accessing an element
puts array[1][0]  # Outputs: 4

We visited the element 4 in the array by its position. The number 1 inside the first square brackets refers to the second inner array, and 0 refers to the first element of that array.

Updating Multidimensional Arrays

Continuing with the apartment-building analogy, suppose the task was to replace the existing appartment code for appartment 2 with a different value. Here's how we can achieve this:

# Updating an element
array[0][1] = 42
puts array.inspect
Common Built-in Methods

Ruby offers a variety of built-in methods that are handy with multidimensional arrays:

  1. length gives the number of elements in the outer array (the number of floors). Note that It does not account for how many elements are inside each nested array (apartments). For example:
    array = [[1, 2], [3, 4, 5], [6]]
    puts array.length  # Outputs: 3 (three outer elements)
    puts array[1].length  # Outputs: 3 (three inner elements in the second array)
  2. push: With push, we can add a new floor and units on that floor to our 'apartment building.'
    # Adding a new row to our array
    array.push([10, 11, 12])
    puts array.inspect
  3. delete: We can rely on delete to help us get rid of a specific element in our 'apartment building.'
    # Removing an element
    array[1].delete(42) # Removes the updated unit from a previous example
    puts array.inspect
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal