0
0
Rubyprogramming~3 mins

Why Compact for removing nil values in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could clean your data with just one simple command?

The Scenario

Imagine you have a list of items, but some are missing or empty (nil). You want to use only the real items, but you have to check each one by hand.

The Problem

Manually checking each item is slow and tiring. You might forget some, make mistakes, or write long code that is hard to read.

The Solution

The compact method quickly removes all the nil values from your list in one simple step, making your code clean and easy.

Before vs After
Before
clean_list = []
list.each do |item|
  clean_list << item unless item.nil?
end
After
clean_list = list.compact
What It Enables

You can focus on working with real data only, without worrying about empty or missing values slowing you down.

Real Life Example

When collecting user inputs, some answers might be missing. Using compact helps you quickly get only the answers that were actually given.

Key Takeaways

Manually removing nil values is slow and error-prone.

compact removes all nils in one simple call.

This makes your code cleaner and easier to understand.