Breaking down Ruby array with hashes inside.
When I first saw my first array with hashes inside, I was very confused and intimated. Take a look at employees array below.
It’s hard to spot the commas as the code has hashes in arrays and arrays in hashes. To break this down, I first tried to ask myself questions regarding the data presented in the employees array.
Question: What are names of Taylor Soft’s children?
Doing ‘employees’ is the first item in the array and it returns a hash. Knowing that we have hash allows us to use key value such as ‘employees[‘Taylor Soft’]’. This also returns a hash and ‘employees[‘Taylor Soft’][‘children’]’ finally returns us to the list of children ‘[“Mary”, “Joseph”]’.
Question: What are names of Ms. Betty Rose’s children?
Now it seems easy, ‘employees[‘Ms. Betty Rose’][‘children’]’ returns => [“John”].
My take away is that if you know you are in an array it will be a number in the brackets and if you are in a hash it will be a key in the brackets. If I’m ever lost, I use the ‘.class’ method. Want more practice? Check out this gem.