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:
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.
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.
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.
In this example, array_hash stores arrays under the keys "numbers" and "letters," making it possible to access organized lists by key.
