👨🏿‍💻
Learn
  • Learn And The Power Of Community
  • Intro
    • learn-co-curriculum/welcome-to-learn-verified
    • learn-co-curriculum/your-first-lab
    • learn-co-curriculum/environment-setup
  • Intro to tic tac toe
    • matz-readme
    • what-is-a-program?
    • hello world
    • Intro to irb
    • Reading-error-messages
    • Data-types
    • variable
    • Variable-assignment lab
    • String interpolation
    • Interpolation-super-power
    • Welcome to tic tac toe
    • Array
    • Tic tac toe board
    • Intro to methods
    • Puts print and return
    • Intro-to-tdd-rspec-and-learn
    • Methods and arguments
    • Say hello (lab)
    • Methods-default-arguments
    • ttt-3-display_board-example
    • ttt-4-display-board-rb
    • Intro-to-cli-applications
    • Greeting-cli
    • cli-applications in Ruby
    • Ruby-gets-input
    • Tic tac toe move
    • Truthiness-in-ruby-readme
    • booleans
    • conditional (if)
    • ttt-6-position-taken
    • ttt-7-valid-move
    • rspec-fizzbuzz
    • Looping-introduction
    • Loop
    • while-and-until-loop
    • Tic Tac Toe Turn lab
    • looping-while-until lab
    • Tic Tac Toe Play Loop (lab)
    • Tic Tac Toe Current Player (lab)
    • Intro to ruby iterators
    • Nested Arrays
    • Boolean Enumerators
    • Search Enumerators
    • Tic Tac Toe Game Status
    • tic-tac-toe
  • OOP tic tac toe
    • intro to oop
    • Intro-to-classes-and-instances
    • Classes-and-instances-lab
    • Instance-methods
    • Instance-methods-lab
    • Object Attributes
    • object-attributes-lab
    • Object Initialization
    • Object-initialize-lab
    • oop barking dog lab
    • Procedural-vs-oop
    • oop tic tac toe
  • Git and github
    • Intro to Version Control
    • Git Repository Basics
    • Git-basics-quiz
    • Forks-and-clones
    • Git Remotes and Github
    • Git Remotes and Github Codealong
    • Thinking Ahead: GitHub as Career Differentiator
    • Github Pull Requests
    • Git Collaboration
    • Git-collaboration-quiz
    • Git Basics Quiz
  • HTML
    • A-quick-tour-of-the-web
    • The-web-is-made-of-strings
    • What-makes-the-web-possible?
    • html-introduction
    • Your first-html-tag-lab
    • Nested-tags-and-attributes
    • Well-formed-html-document-lab
    • HTML elements types overview
    • Researching-HTML-elements
    • Separation-of-content-and-presentation
  • CSS
    • Introduction-to-css
    • introduction-to-css-code-along
  • Procedural Ruby
    • Regex-what-is-a-pattern
    • Regex-basics
    • Regex-lab
    • Regex-match-scan-grep-methods
    • learn-co-curriculum/method-arguments-lab
    • Method-scope
    • Return Values Lab
    • Debugging-with-pry
    • Method-scope-lab
    • Truthiness-code-challenge
    • If Statements Lab
    • Case-statements
    • Case-statements-quiz
    • Logic and Conditionals Quiz
    • Ternary Operators and Statement Modifiers lab
    • Looping Lab
    • looping-quiz
    • learn-co-curriculum/looping-times
    • countdown-to-midnight lab
    • Array introduction
    • Using Arrays
    • Array-CRUD-lab
    • Array-methods
    • Array-methods-lab
    • Square array lab
    • Collect and Return Values
    • Collect Lab
    • Badges and Schedules Lab
    • Oxford comma lab
    • Deli counter lab
    • Reverse Each Word Lab
    • Yield-and-blocks
    • Each Lab
    • Return from Yield Statements
    • My All? Lab
    • My Find Lab
    • Cartoon Collections Lab
    • Enumerators Code Challenge
    • Prime? Lab
    • Sorting
    • Sorting Lab
    • Introduction to Hashes
    • Using Hashes lab
    • Ruby-symbols
    • Hash iteration
    • Hash Iteration Lab
    • Hash Iteration with Collect
    • Intro to Nested Hashes
    • Building Nested Hashes
    • Building Nested Hashes Lab
    • Nested Hash Iteration
    • Nested Hashes Lab
    • Multitype Collections Lab
    • Iterating over Nested Hashes Codealong
    • Other Hashes Codealong
    • Hashes Manipulation Lab
  • OOP Ruby
    • OO Ruby Video: Object Orientation Overview
    • Object Accessors
    • Instance Variables lab
    • Video Review: Object Properties
    • Meowing Cat
    • Intro to Object Orientation - Ruby
    • oo basics lab
    • OO Basics with Class Constants
    • Self
    • OO School Domain lab
    • OO Counting Sentences lab
    • Class Variables and Methods
    • Class Variables and Methods Lab
    • Remembering Objects
    • Puppy Lab
    • Advanced Class Methods
    • Advanced Class Methods Lab
    • Video Review: Object Models
    • OO Email Parser lab
    • OO Anagram Detector lab
    • OO Cash Register lab
    • Intro to Object Relationships
    • Belongs to Object Lab
    • Has Many Object
    • Has Many Object Lab
    • Collaborating Objects Review
    • Collaborating Objects Lab
    • OO My Pets
    • oo kickstarter lab
    • OO Banking lab
    • Has Many Objects Through
    • Has Many Objects Through Lab
    • Intro to Inheritance
    • Intro to Inheritance Lab
    • Super
    • Super Lab
    • Intro to Modules
    • Intro to Modules Lab
    • Mass Assignment
    • Mass Assignment and Metaprogramming
    • Mass Assignment Lab
    • Custom Errors lab
    • OO Triangle lab
  • Scraping and project
    • Gems and Bundler
    • Scraping
    • Scraping Lab
    • Kickstarter Scraping Lab
    • Video Review: Object Orientation and Scraping
    • OO Ruby Object Orientation Video Review
    • Music Library CLI
    • Video Review: Music Library CLI
    • Tic-tac-toe with AI project
    • Student Scraper
    • CLI Data Gem Portfolio Project
    • CLI Data Gem Walkthrough
    • CLI Data Gem Walkthrough: Creating a CLI Scraper Gem
    • Common Anti-Patterns in CLI Data Gem
    • Student Example 1: Refactoring CLI Gem
    • Student Example 2: Refactoring CLI Gem
  • SQL
    • What is SQL
    • SQL Intro and Installation
    • SQL Database Basics
    • SQL Databases and Text Editors
    • SQL Data Types
    • SQL Inserting, Updating, and Selecting
    • Basic SQL Queries
    • SQL Aggregate Functions
    • SQL Aggregate Functions Lab
    • SQL Bear Organizer Lab
    • Edgar Codd and Table Relations
    • Table Relations
    • SQL JOINS
    • SQL Complex Joins
    • SQL Join Tables
    • Grouping and Sorting Data
    • SQL Joins Review Lectures
    • SQL Crowdfunding Lab
    • SQL Library Lab
    • Pokemon Scraper Lab
  • ORM And Active record
    • Why an ORM is Useful
    • Mapping Ruby Classes to Database Tables
    • Mapping Classes to Tables Lab
    • Mapping Database Tables to Ruby Objects
    • Mapping Database Rows to Objects Lab
    • Updating Records in an ORM
    • Updating Records in an ORM Lab
    • Preventing Record Duplication
    • ORMs Lab: Bringing It All Together lab
    • Dynamic ORMs
    • Dynamic ORMs with Inheritance
    • ActiveRecord Mechanics
    • Translating from ORM to ActiveRecord
    • Intro to Rake
    • Mechanics of Migrations
    • Writing Our Own Migrations
    • Migrations and Active Record Lab
    • ActiveRecord CRUD Lab
    • Advanced Finding Lab
    • ActiveRecord Associations
    • ActiveRecord Associations Lab
    • ActiveRecord Associations Lab II
    • ActiveRecord Associations Video Review
    • ActiveRecord Associations Video Review II
    • Video Review: Aliasing ActiveRecord Associations
    • Video Review: Blog CLI with ActiveRecord and Associations
  • Rack
    • How the Internet Works
    • Increasing Layers of Abstraction
    • Inspecting the Web with Rack (lab)
    • The HTTP Request
    • Dynamic URL Routes
    • Dynamic Web Apps with Rack (lab)
    • Rack Responses Lab
    • Rack Routes and GET Params Lab
    • HTTP Status Codes
    • Dynamic URLs and Status Codes Lab
    • Video Review: How The Web Works, Pt 1
    • Video Review: How the Web Works, Pt 2
  • Html
    • How the Web Works
    • Site Planning
    • HTML Fundamentals
    • HTTP Status Codes
    • video review how the web works pt 1
    • How the Web Works, Part 2: Overview
    • Setting Up a New Site
    • Document Structure
    • Text Formatting
    • HTML Tables
    • Html-images
    • HTML Links
    • Html backing-up changes
    • HTML Validation
    • Quiz - HTML Fundamentals
    • Dev Tools Super Power
    • HTML Lists
    • Html issue bot 9000 (lab)
    • HTML Forms and Iframes
    • HTML Map and Contact Form Code-along
    • HTML5 Media
    • HTML5 Video Embed Code-Along
    • HTML5 Semantic Elements
    • HTML5 Semantic Containers Code-along
    • HTML5 Quiz
  • CSS
    • CSS Fundamentals
    • CSS Styling Code Along
    • My Little Rainbow
    • CSS Kitten Wheelbarrow
    • CSS Graffiti Override Lab
    • CSS Issue Bot 9000
    • Your first deployment
    • The Box Model
    • Layout Types
    • Float
    • Clearfix
    • Centering
    • Column Structure
    • CSS Columns Code Along Exercise (lab)
    • Box Model & Page Layout
    • Using Z Index
    • Positioning
    • ZHW Shoes Layout (lab)
    • Zetsy (lab)
    • CSS Box Style Code Along
    • Animal Save (lab)
    • Building Responsive Sites
    • Intro to Responsive Media
    • CSS Media Queries
    • Working with Responsive Type
    • Responsive layout
    • The Viewport Property
    • Responsive Features Code-Along (lab)
    • Bootstrap Introduction
    • Bootstrap Code-Along
    • Bootstrap Grid System
    • Grid Layout Code-Along
    • Bootstrap Navbar Code-Along
  • Sinatra
    • What is Sinatra?
    • Sinatra From Scratch
    • Using the Shotgun Development Server (lab)
    • Sinatra Basics
    • Sinatra Hello World Basics (lab)
    • Routes in Sinatra
    • Sinatra Routes Lab
    • Intro To MVC
    • Sinatra MVC File Structure (lab)
    • Sinatra Views: Using ERB
    • Sinatra Views (lab)
    • Sinatra Basic Views Lab
    • Sinatra Views Lab II
    • Intro To Capybara
    • Dynamic Routes in Sinatra
    • HTML Forms and Params
    • Passing Data Between Views and Controllers in Sinatra
    • Sinatra Forms Lab
    • Sinatra Yield Readme
    • Integrating Models Sinatra Code-along
    • Sinatra MVC Lab - Pig Latinizer
    • Sinatra Basic Forms Lab
    • Sinatra Forms
    • Nested Forms Readme
    • Sinatra Nested Forms Lab: Pirates!
    • Lab Review-- Sinatra Nested Forms Lab: Pirates
    • Sinatra Nested Forms Lab: Superheroes!
    • Sessions and Cookies
    • Mechanics of Sessions
    • Sinatra Basic Sessions Lab
    • Using Sessions
    • Sinatra and Active Record CRUD
    • Sinatra Activerecord Setup
    • Sinatra ActiveRecord CRUD
    • User Authentication in Sinatra
    • Sinatra Sessions Lab - User Logins
    • Securing Passwords
    • Secure Password Lab
    • Sinatra Authentication- Overview
    • RESTful Routes
    • Restful Routes Basic Lab
    • Sinatra ActiveRecord Associations: Join Tables
    • Using Tux in Sinatra with ActiveRecord
    • ActiveRecord Associations in Sinatra
    • Sinatra Multiple Controllers
    • Sinatra and Active Record: Associations and Complex Forms
    • Sinatra Playlister (lab)
    • Welcome to NYC Sinatra! (lab)
    • Building a Site Generator, Part 1- Overview
    • Building a Site Generator, Part 2- Overview
    • Fwitter Group Project
  • Rails
    • Welcome To Rails
      • Rails Application Basics
      • Rails Static Request
      • Rails Hello World Lab
      • Rails Model View Controller
      • Intro to Rails- Overview
    • Intro to REST
    • Active Record Models and Rails
    • ActiveRecord Model Rails Lab
    • RESTful Index Action Lab
    • Rails Dynamic Request
    • Rails Dynamic Request Lab
    • Rails URL Helpers
    • Rails URL Helpers Lab
    • Rails form_tag
    • Rails form_tag Lab
    • Create Action
    • Create Action Lab
    • Index, Show, New, Create Lab
    • Edit/Update Action
    • form_for on Edit
    • Strong Params Basics
    • form_for Lab
    • Rails Generators
    • CRU with form_for Lab
    • Resource and Scaffold Generator
    • Rails Blog scaffold
    • Todo mvc assets and managing lists
    • Rails Forms Overview
    • ActiveRecord Validations
    • ActiveRecord Validations Lab
    • Validations in Controller Actions
    • Validations In Controller Actions Lab
    • Validations with form_tag
    • Validations with form_for
    • DELETE Forms and Requests
    • Testing in Rails
    • Validations with form_tag
    • CRUD With Validations Lab
    • Join the Fun rails
    • Activerecord lifecycle reading
    • Displaying Associations Rails
    • Active Record Associations Review
    • Forms And Basic Associations Rails
    • Forms And Basic Associations Rails Lab
    • Basic Nested Forms
    • Displaying Has Many Through Rails
    • Displaying Has Many Through Rails Lab
    • Has Many Through Forms Rails
    • Has Many Through Forms Rails Labs
    • Has Many Through in Forms Lab Review- Overview
    • Deep Dive into Nested Forms- Overview
    • Layouts And Templates in Rails
    • Rails Layouts And Templates Lab
    • Simple Partials
    • Simple Partials Lab
    • Partials with Locals
    • Partials with Locals
    • Refresher on MVC
    • Refactoring Views With Helpers
    • Refactoring Views With Helpers Lab
    • Model Class Methods
    • Optimal Queries using Active Record (lab)
    • Routing And Nested Resources
    • Nested Resource Routing Lab
    • Modifying Nested Resources
    • Modifying Nested Resources Lab
    • Namespaced Routes
    • Namespaced Routes Lab
    • Todomvc 2 lists have items
    • TodoMVC 3: Mark Items Complete
    • Todomvc 4 refactoring with partials and helpers
    • Todomvc 5 deleting items
    • Introduction to Authentication and Authorization
      • Cookies and sessions
      • Cookies and Sessions Lab
      • Sessions Controller
      • Sessions Controller Lab
      • Login Required Readme
      • Login Required Lab
      • Using has_secure_password
      • Has_secure_password lab
      • Authentication- Overviewn
      • OmniAuth
      • Omniauth Lab
      • Omniauth review lecture in todomvc
      • Authentication and authorization recap and gems
    • Rails Amusement Park lab
    • How to Find Gems
  • JavaScript
    • Intro to JavaScript
      • JavaScript Data Types
      • JavaScript Data Types Quiz
      • JavaScript Variables
      • JavaScript Comparisons
      • Conditionals
      • Logical Operators
      • Functions
      • Intro to Debugging
      • Intro to Testing
      • JavaScript Basics Quiz
    • Scope
      • Scope chain
      • JavaScript Practice Scope Lab
      • Lexical scoping
      • Errors and Stack Traces
      • Hoisting
    • Arrays And Objects
      • Objects
      • JavaScript: Objects and Arrays Quiz
      • Object Iteration
      • JavaScript Logging
      • Traversing Nested Objects
      • Filter
      • Map
    • Functions Revised
      • First-Class Functions Lab
      • First-Class Functions
      • First-Class Functions Practice
      • First-Class Functions Practice Lab
    • OOP
      • Creating Objects
      • Object Methods and Classes
      • Using Prototypes
      • Using Classes in Javascript
      • JavaScript This Walkthrough
      • This Code-along
      • Bind, Call, and Apply Readme
      • Bind, Call, Apply Lab
      • Object Relations
      • Association Methods in Javascript
      • Class Relations Lab
      • JavaScript Closures and Higher Order Functions
      • Closures Lab
      • JavaScript Arrow Functions
      • Daily Lunch Lab
    • DOM
      • Introduction to the DOM
      • Introduction to the DOM Lab
      • More on the DOM
      • Creating and Inserting DOM Nodes
      • The DOM Is a Tree
      • Listening to Nodes
      • Modify HTML With jQuery
      • Modifying HTML Lab
      • jQuery Selectors
      • Document.ready
      • Acting On Events Lab
      • DOM Quiz
    • Templates
      • Introduction to CSS
      • CSS Quiz
      • CSS Libraries
      • CSS Libraries Lab
      • Intro to Templates
      • Template Engines
      • Template Engines Lab
      • Advanced Templating
      • Advanced Templating Lab
    • Asynchronous JavaScript
      • Intro to XHR Code Along
      • Hitting APIs Lab
      • Advanced AJAX Lab
      • AJAX and Callbacks
      • AJAX and Callbacks Lab
      • REST Refresher
      • REST Quiz
      • Fetch
      • JavaScript fetch() Lab
      • Intro to Mocha
      • Testing with Spies
      • Testing with Mocks and Stubs
  • Rails and JavaScript
Powered by GitBook
On this page
  • Objectives
  • What is a Nested Array?
  • Why Use a Nested Array?
  • Reading and Writing with Nested Arrays
  • Accessing Data from a Nested Array
  • Adding Data to a Nested Array
  • Iterating Over Nested Arrays
  • More Nested Arrays
  • When to Use a Multidimensional Array
  • When Not to Use a Multidimensional Array
  1. Intro to tic tac toe

Nested Arrays

Objectives

  1. Create nested, or multidimensional, arrays.

  2. Read data from a nested array.

  3. Write data to a nested array.

  4. Iterate over a nested array.

What is a Nested Array?

An array is like a list but in code form. It is a way for your program to store pieces of data as a collection. Arrays can contain any combination of Ruby data types -- booleans, integers, strings, or even other collections in the form of nested arrays and hashes.

Arrays are declared as a comma-separated list of variable names or literal values wrapped in square brackets. For example:

students = ["Mike", "Tim", "Monique"]

We know that arrays can contain any type of data, including other arrays. Let's see that in action:

nested_students = [
  ["Mike", "Grade 10", "A average"],
  ["Tim", "Grade 10", "C average"],
  ["Monique", "Grade 11", "B Average"]
]

A nested, or multidimensional array, is an array whose individual elements are also arrays.

Why Use a Nested Array?

Nested arrays are useful for storing groups of similar data. One example of nested array usage comes to us from the Google Maps API. Google Maps provides a JavaScript function that you, the developer, can use to add Google Maps to your own website. Don't worry about JavaScript right now; just understand that a JavaScript function is like a Ruby method.

The map-making function (or method, as we're going to think of it) was designed to take in an argument of a nested array -- an array in which each index element is an array containing a place name, latitude, and longitude. In other words, something that looks like this:

location_array =  [
  ["The Flatiron School", 40.705329, -74.013970],
  ["Disney World", 28.385233, -81.563874]
]

Reading and Writing with Nested Arrays

Accessing Data from a Nested Array

To access data from and add data to (i.e., "read and write") a nested array, we use the same methods we've been using to deal with one-dimensional arrays.

Let's stick with our students and nested_students arrays for now. To grab an element out of the students array, we use bracket notation plus the index number of the element we want.

students = ["Mike", "Tim", "Monique"]
students[0] #=> "Mike"

To access the same value, "Mike", from our nested_students array, we double up on bracket notation to drill down into the second, nested level of the array:

nested_students = [
  ["Mike", "Grade 10", "A average"],
  ["Tim", "Grade 10", "C average"],
  ["Monique", "Grade 11", "B average"]
]

nested_students[0][0] #=> "Mike"

The first set of brackets refers to the top level of the nested_students array -- the array containing our three nested arrays.

nested_students[0] #=> ["Mike", "Grade 10", "A average"]

We can see that the return value of nested_students[0] is the element at index 0 of the nested_students array. The returned element is an array that looks like this:

["Mike", "Grade 10", "A average"]

If you set the return value of calling nested_students[0] equal to a variable, we can then operate on it with further bracket notation:

mike = nested_students[0]
mike[0] #=> "Mike"

The syntax that we used earlier -- nested_students[0][0] -- is simply the chaining of method calls. We are calling the [0] method on the value returned by nested_students[0].

Let's try a different example. This time, let's write a line of code that returns the grade level of the last student in the nested_students array. Give it a shot in IRB before reading on.

nested_students = [
  ["Mike", "Grade 10", "A average"],
  ["Tim", "Grade 10", "C average"],
  ["Monique", "Grade 11", "B average"]
]

nested_students[2][1] #=> "Grade 11"

First, we are accessing the element at index 2 of the nested_students array, ["Monique", "Grade 11", "B average"]. That element happens to be an array with three elements, the second of which (the element at index 1) is the grade level of the student. So nested_students[2] grabs us the array that describes the last student in the list and chaining on [1] grabs the value of the element at index 1 of that array -- the string "Grade 11".

Now that we are getting comfortable retrieving data from a nested array, let's work on adding data to such an array.

Adding Data to a Nested Array

To add data to a nested array, we can use the same <<, or shovel, method we use to add data to a one-dimensional array.

To add another student to our students array:

students = ["Mike", "Tim", "Monique"]
students << "Sarah"
students #=> ["Mike", "Tim", "Monique", "Sarah"]

To add an element to an array that is nested inside of another array, we first use the same bracket notation as above to dig down to the nested array, and then we can use the << on it. To illustrate, let's add another piece of info, "Class President", to the nested array that describes Monique.

First, we have to access Monique's array.

Then -- bam! -- we hit it with the shovel, <<.

nested_students[2] << "Class President"

Now, our nested_students array looks like this:

nested_students = [
  ["Mike", "Grade 10", "A average"],
  ["Tim", "Grade 10", "C average"],
  ["Monique", "Grade 11", "B average", "Class President"]
]

Iterating Over Nested Arrays

What if we want to add data to every array that is nested within the parent array? It would be very tedious if we had to calculate the length of the array and then, one-by-one, modify each individual child array using bracket notation and the << method.

When we are dealing with a one-dimensional array and want to do something to every element, we iterate, using methods like #each and #collect. If, for example, we wanted to puts out every member of the students array, we could do so like this:

students.each do |student|
  puts student
end

In order to manipulate or operate on each element of a nested array, we must first dig down into that level of the array. For example, run the following code in IRB:

nested_students = [
  ["Mike", "Grade 10", "A average"],
  ["Tim", "Grade 10", "C average"],
  ["Monique", "Grade 11", "B average", "Class President"]
]

nested_students.each do |student_array|
  # #inspect returns a human-readable representation
  # of the array
  puts student_array.inspect
end

The .each method prints out each nested array separately and then returns the original array:

["Mike", "Grade 10", "A average"]
["Tim", "Grade 10", "C average"]
["Monique", "Grade 11", "B average", "Class President"]
#  => [["Mike", "Grade 10", "A average"], ["Tim", "Grade 10", "C average"], ["Monique", "Grade 11", "B average", "Class President"]]

In the example above, we are iterating through the list of arrays that make up the top level of the nested_students array. If we want to iterate through the elements inside each child array, we add a second layer of iteration inside the first:

nested_students = [
  ["Mike", "Grade 10", "A average"],
  ["Tim", "Grade 10", "C average"],
  ["Monique", "Grade 11", "B average", "Class President"]
]

nested_students.each do |student_array|
  student_array.each do |student_detail|
    puts student_detail
  end
end

Copy and paste the above code into IRB. You should see the following output:

Mike
Grade 10
A average
Tim
Grade 10
C average
Monique
Grade 11
B average
Class President

More Nested Arrays

Let's take a look at some multidimensional arrays that have an even deeper nesting structure than the 2D examples we've seen so far.

very_nested_array = [
  ["this", "is", "the", "first", "child", ["this", "is", "the", "grandchild"]],
  ["now", "we're", "back", "in", "the", "second", "level", ["now", "we're", "back", "in", "the", "grandchild", "level"]]
]

In this array, we have the top-level, or parent array, containing two child arrays. The array that is the first element of this parent array (accessed via very_nested_array[0]) contains six elements, the last of which (accessed via very_nested_array[0][5]) is yet another array. The array that is the second element of the parent array contains eight elements, the last of which is another third-level array. Here, we have three levels of nesting.

When to Use a Multidimensional Array

Multidimensional arrays, like the deeply nested one above, are useful for storing hierarchical data. Any collection of information that you can picture like a tree is a good candidate for a nested array.

Let's take, for example, a music library. There are artists (top level) who created albums (second level) that contain songs (third level). You can visualize the structure like this:

And so on, for the various artists in the library. This data structure is considered hierarchical. To illustrate, let's add a second artist and recreate our two-act library as a nested array:

music_library = [["Adele", ["19", ["Day Dreamer", "Best for Last"]], ["21", ["Rolling in the Deep", "Rumor Has It"]]], ["Beyonce", ["4", ["1 + 1", "Countdown"]], ["Beyonce", ["Haunted", "Pretty Hurts"]]]]

When working with multidimensional arrays, it can be difficult to read through the data structure in a way that makes sense. A useful tactic is to format the array such that each nested level is placed on its own line. This can make complex structures much easier to read:

music_library = [
  ["Adele",
    ["19",
      ["Day Dreamer", "Best for Last"]
    ],
    ["21",
      ["Rolling in the Deep", "Rumor Has It"]
    ]
  ],
  ["Beyonce",
    ["4",
      ["1 + 1", "Countdown"]
    ],
    ["Beyonce",
      ["Haunted", "Pretty Hurts"]
    ]
  ]
]

Let's try iterating over our music_library array.

music_library.each do |artist_array|
  # Iterate through the parent array, returning each element sequentially
  # For the first pass: artist_array = music_library[0] = ["Adele", ["19", ["Day Dreamer", "Best for Last"]], ["21", ["Rolling in the Deep", "Rumor Has It"]]]

  artist_array.each do |artist_element|
    # Iterate through each element of the child (second-level) array returned by the above parent iteration
    # For the first pass: artist_element = artist_array[0] = music_library[0][0] = "Adele"

    if artist_element.class != Array
      puts "Artist: #{artist_element}"
    else
      artist_element.each do |album_element|
        # Iterate through each element of the grandchild (third-level) array
        # For the first pass (that makes it past the "if" clause and reaches this "else" clause):
        # album_element = artist_element[0] = artist_array[1][0] = music_library[0][1][0] = "19"

        if album_element.class != Array
          puts "Album: #{album_element}"
        else
          album_element.each do |song_element|
            # For the first pass (that makes it past the "if" clause and reaches this "else" clause):
            # song_element = album_element[0] = artist_element[1][0] = artist_array[1][1][0] = music_library[0][1][1][0] = "Day Dreamer"

            puts "Song: #{song_element}"
          end
        end
      end
    end
  end
end

We begin by iterating over the first child array, the array that contains all of the information about a particular artist:

music_library.each do |artist_array|
  artist_array.each do |artist_element|
    # etc...
  end
end

At this level, we are accessing the two child arrays that make up the first tier of the music_library. On the first pass/step/time through the iteration of music_library, artist_array is equal to ["Adele", ["19", ["Day Dreamer", "Best for Last"]], ["21", ["Rolling in the Deep", "Rumor Has It"]]]. On the first pass through the iteration of artist_array, artist_element is equal to "Adele".

We have two checks to put in place if we want to keep iterating. Some of the elements in the artist_array array are other arrays. These need to be iterated over so that we can access what is inside (i.e., information about the albums and songs). However, some of the elements are just strings. "But we can't iterate over a string," you mumble incredulously. Well, you're absolutely right. Since we can't iterate over a string... we won't! Instead, we'll use if/else statements to check whether an element is an array. If it is, we'll iterate over it; if it isn't, we'll simply puts it out to the terminal.

music_library.each do |artist_array|
  artist_array.each do |artist_element|
    if artist_element.class != Array # Check whether the element is not an array
      puts "Artist: #{artist_element}"
    else # I.e., if the element is an array
      artist_element.each do |album_element|
        # Third level of iteration
      end
    end
  end
end

At the third level of iteration (marked in the above code), we are operating on the grandchild arrays nested inside the child arrays that describe each artist that are nested inside the parent music_library array. On the first pass through the second-level iteration, artist_element is equal to "Adele", which is not an array and is therefore printed out to the terminal by the puts "Artist: #{artist_element}" line. On the second pass, artist_element is equal to ["19", ["Day Dreamer", "Best for Last"]], which is an array and therefore fails the if clause's condition, skipping to the else clause and triggering the third-level iterative process.

Once again, some of the members of this array are other arrays, and some are strings. Let's reuse our if/else logic to determine whether we should iterate over each individual element passed into album_element:

# ...
artist_element.each do |album_element|
  if album_element.class != Array
    puts "Album: #{album_element}"
  else
    album_element.each do |song_element|
      # Fourth and final level of iteration
    end
  end
end
# ...

The album_element arrays are at the deepest level of our music_library. There are no more arrays to identify and iterate over, so all we need to do inside that fourth iteration is puts out each song_element.

Let's take a look at the whole thing again:

music_library.each do |artist_array|
  artist_array.each do |artist_element|
    if artist_element.class != Array
      puts "Artist: #{artist_element}"
    else
      artist_element.each do |album_element|
        if album_element.class != Array
          puts "Album: #{album_element}"
        else
          album_element.each do |song_element|
            puts "Song: #{song_element}"
          end
        end
      end
    end
  end
end

Iterating over multidimensional arrays is tough. Try opening up a new Ruby file in your text editor and writing a method that contains the above code.

When Not to Use a Multidimensional Array

Four levels deep is about as deep as you want to go when constructing multidimensional arrays. As you can see, things can quickly get messy. If you have more hierarchical data than can fit in a 4D array, it might be better to try using a dictionary-like data structure, called a hash, instead.

PreviousIntro to ruby iteratorsNextBoolean Enumerators

Last updated 5 years ago

View on Learn.co and start learning to code for free.

View on Learn.co and start learning to code for free.

Multidimensional Arrays
Nested Arrays
Structure of Data