0
0
Rubyprogramming~15 mins

Flat_map for nested flattening in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Flat_map for nested flattening
📖 Scenario: You work at a bakery that sells boxes of assorted cookies. Each box contains different types of cookies in separate trays. You want to list all cookie types available in all boxes in one flat list.
🎯 Goal: Use Ruby's flat_map method to flatten a nested array of cookie trays into a single array of cookie types.
📋 What You'll Learn
Create a variable cookie_boxes that holds an array of arrays, each inner array representing cookie types in a box.
Create a variable all_cookies that uses flat_map on cookie_boxes to flatten all cookie types into one array.
Print the all_cookies array.
💡 Why This Matters
🌍 Real World
Flattening nested lists is common when you have grouped data but want to work with all items together, like listing all products from multiple categories.
💼 Career
Understanding how to flatten nested data structures helps in data processing, report generation, and simplifying complex data for easier use in software development.
Progress0 / 4 steps
1
Create the nested array of cookie trays
Create a variable called cookie_boxes and set it to an array containing these arrays exactly: ["Chocolate Chip", "Oatmeal"], ["Peanut Butter", "Sugar"], and ["Snickerdoodle"].
Ruby
Need a hint?

Remember to use square brackets for arrays and double quotes for strings.

2
Prepare to flatten the nested array
Create a variable called all_cookies and set it to nil for now. This will hold the flattened list later.
Ruby
Need a hint?

Just create the variable and assign nil for now.

3
Use flat_map to flatten the nested array
Set the variable all_cookies to the result of calling flat_map on cookie_boxes with a block that returns each inner array as is.
Ruby
Need a hint?

Use flat_map with a block that takes each tray and returns it.

4
Print the flattened list of cookies
Write a puts statement to print the all_cookies array.
Ruby
Need a hint?

Use puts all_cookies to print each cookie type on its own line.