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[0]’ 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[0][‘Taylor Soft’]’. This also returns a hash and ‘employees[0][‘Taylor Soft’][‘children’]’ finally returns us to the list of children ‘[“Mary”, “Joseph”]’.

irb terminal

Question: What are names of Ms. Betty Rose’s children?

Now it seems easy, ‘employees[2][‘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.

Show your support

Clapping shows how much you appreciated Anna Natorilla’s story.