Exploring Compound Data Structures in Ruby

Introduction

Welcome to our exploration of Compound Data Structures in Ruby! Having navigated through Sets, Arrays, and using freeze for immutability, we’ll now dive into nested hashes and nested arrays. These structures allow us to manage complex, hierarchical data, which is essential in many real-world scenarios. This lesson will guide you through a recap of the basics, as well as the creation and modification of nested hashes and arrays.

Recap: Hashes, Arrays, and Nested Structures

As a quick recap, Arrays are ordered collections of elements, while Hashes store data in key-value pairs. Both of these structures can be nested to represent more complex data.

Example: School Directory

Here’s a simple example of a school directory using a hash where each grade level contains an array of student names:

school_directory = {
  'Grade1' => ['Amy', 'Bobby', 'Charlie'],
  'Grade2' => ['David', 'Eve', 'Frank'],
  'Grade3' => ['George', 'Hannah', 'Ivy']
}

puts school_directory['Grade1']  # Output: ["Amy", "Bobby", "Charlie"]

This nested structure organizes student names by grade level, making it easy to access the list of students in each grade.

Creating Nested Hashes and Arrays

Creating nested structures in Ruby is straightforward, following the same syntax as non-nested versions.

Nested Hash: A hash that contains other hashes as values. This structure is useful for organizing data into categories.

nested_hash = {
  'fruit' => {
    'apple' => 'red',
    'banana' => 'yellow'
  },
  'vegetable' => {
    'carrot' => 'orange',
    'spinach' => 'green'
  }
}

puts nested_hash.inspect
# Output: {"fruit"=>{"apple"=>"red", "banana"=>"yellow"}, "vegetable"=>{"carrot"=>"orange", "spinach"=>"green"}}

In this example, nested_hash is a hash with categories "fruit" and "vegetable," each containing its own key-value pairs.

Nested Array: An array that contains other arrays as elements. This structure is useful when organizing lists within a larger list.

nested_array = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

puts nested_array.inspect  # Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Here, nested_array contains three inner arrays, each with a set of numbers.

Combining Hashes and Arrays: Hashes can store arrays as values, allowing for a hybrid data structure that combines lists and key-value pairs.

array_hash = {
  'numbers' => [1, 2, 3],
  'letters' => ['a', 'b', 'c']
}

puts array_hash.inspect  # Output: {"numbers"=>[1, 2, 3], "letters"=>["a", "b", "c"]}

In this example, array_hash stores arrays under the keys "numbers" and "letters," making it possible to access organized lists by key.

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