Nested Collections
What are you going to learn?
- Understand how to read and manipulate nested collections
- Perform operations on nested data collections
Before jumping into the lesson, you may want to read the arrays and hash content.
Arrays in Arrays
As we move forward with software, you may find that data collections start to become a little bit more complex, whether the ones we create or third-party.
Take this simple example, and try to answer the following:
nested_collection = [["burguer", "pizza", "hot dog"], ["coke", "water", "beer"]]
- What would the method
countonnested_collectionreturn? - How would you access the
pizzaelement? - How would you add another set of data?
Hash in Arrays
heroes = [{name: "Iron Man"}, {name: "Hulk"}]
- What would the method
countonheroesreturn? - How would you access the
Hulkelement? - How would you change
"Iron Man"to"Black Widow"?
Hash with Arrays
chinese_food_box = { base: ["rice", "wheat noodles", "egg noodles"], protein: ["fish", "shrimp", "beef", "chicken"], toppings: ["onion", "brocoli", "peanuts", "carrot", "potato"], sauce: ["teriyaki", "spicy", "cilantro", "soy sauce"] }
- What would the method
countonchinese_food_boxreturn? - How would you add a
extraskey-pair to thechinese_food_boxcollection? - How would you access the
peanutselement? - How would you add another topping?
Hash with Hash
pokemons = { pikachu: { level: 32, attacks: ["thundershock", "thunder punch", "surf"] }, charizard: { level: 54, attacks: ["dragon claw", "blast burn", "firespin"] }, gengar: { level: 42, attacks: ["shadow claw", "sludge bomb", "shadow ball"] }, }
- What would the method
countonpokemonsreturn? - How would you add an
attributekey-pair to each pokemon element? - How would you access the
charizardelement attacks? - How would you add another another attack for any pokemon?
Exercises
Remember we have provided a repository with a bunch of exercises for you to complete. You can find it here
You can finde them under /ruby-exercises/Module1/nested-collections.