0
0
Rubyprogramming~5 mins

Compact for removing nil values in Ruby

Choose your learning style9 modes available
Introduction

Sometimes, lists have empty spots called nil in Ruby. compact helps clean the list by removing these empty spots.

When you have a list of items and want to ignore empty or missing values.
When you get data from a form or user input that might have blanks.
When you want to prepare a list for counting or showing only real items.
Syntax
Ruby
array.compact

This method returns a new array without nil values.

It does not change the original array unless you use compact!.

Examples
Removes all nil values and returns [1, 2, 3].
Ruby
[1, nil, 2, nil, 3].compact
All values are nil, so it returns an empty array [].
Ruby
[nil, nil, nil].compact
compact! changes the original array by removing nil values.
Ruby
array = [1, nil, 2]
array.compact!
puts array.inspect
Sample Program

This program shows how compact removes nil values from the list without changing the original.

Ruby
numbers = [10, nil, 20, nil, 30]
clean_numbers = numbers.compact
puts "Original: #{numbers.inspect}"
puts "Cleaned: #{clean_numbers.inspect}"
OutputSuccess
Important Notes

If you want to remove nil values and change the original array, use compact!.

If there are no nil values, compact! returns nil.

Summary

compact removes nil values from arrays.

It returns a new array and keeps the original unchanged.

Use compact! to change the original array directly.