0
0
Rubyprogramming~15 mins

Compact for removing nil values in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Compact for removing nil values
📖 Scenario: You have a list of items where some are missing (nil). You want to clean this list by removing all the missing items.
🎯 Goal: Build a Ruby program that uses compact to remove all nil values from an array.
📋 What You'll Learn
Create an array called items with some nil values
Create a variable called clean_items that uses compact on items
Print the clean_items array
💡 Why This Matters
🌍 Real World
Cleaning data lists by removing missing or empty values is common in many programs, like filtering user inputs or processing data files.
💼 Career
Knowing how to clean arrays efficiently helps in data processing, web development, and scripting tasks where data quality matters.
Progress0 / 4 steps
1
Create the array with nil values
Create an array called items with these exact elements: "apple", nil, "banana", nil, "cherry"
Ruby
Need a hint?

Use square brackets [] to create the array and include nil where needed.

2
Use compact to remove nil values
Create a variable called clean_items and set it to items.compact to remove all nil values
Ruby
Need a hint?

Use the compact method on the items array and assign it to clean_items.

3
Print the cleaned array
Write a puts statement to print the clean_items array
Ruby
Need a hint?

Use puts clean_items to display the array elements, each on its own line.

4
Print the cleaned array as a single line
Write a puts statement to print the clean_items array as a single line using inspect
Ruby
Need a hint?

Use puts clean_items.inspect to print the array on one line with brackets.