0
0
RubyHow-ToBeginner · 3 min read

How to Compact an Array in Ruby: Remove nil Values Easily

In Ruby, you can use the compact method on an array to remove all nil values and get a new array without them. If you want to modify the original array itself, use compact! which changes the array in place.
📐

Syntax

The compact method is called on an array to return a new array without any nil values. The compact! method removes nil values from the original array itself.

  • array.compact - returns a new array without nil values.
  • array.compact! - removes nil values from the same array and returns it, or nil if no changes were made.
ruby
array.compact
array.compact!
💻

Example

This example shows how to use compact to get a new array without nil values, and how compact! modifies the original array.

ruby
arr = [1, nil, 2, nil, 3]
new_arr = arr.compact
puts "Original array: #{arr.inspect}"
puts "New array after compact: #{new_arr.inspect}"
arr.compact!
puts "Original array after compact!: #{arr.inspect}"
Output
Original array: [1, nil, 2, nil, 3] New array after compact: [1, 2, 3] Original array after compact!: [1, 2, 3]
⚠️

Common Pitfalls

A common mistake is expecting compact! to always return the array. It returns nil if no nil values were found and removed. Also, compact does not change the original array, so if you want to keep the changes, assign the result or use compact!.

ruby
arr = [1, 2, 3]
result = arr.compact!
puts result.nil? ? "No nil values removed" : "Nil values removed"
Output
No nil values removed
📊

Quick Reference

Summary of compact methods:

MethodDescriptionReturns
array.compactReturns a new array without nil valuesNew array
array.compact!Removes nil values from the original arrayModified array or nil if no changes

Key Takeaways

Use compact to get a new array without nil values without changing the original.
Use compact! to remove nil values from the original array itself.
compact! returns nil if no nil values were found to remove.
Remember to assign the result of compact if you want to keep the changes.
Both methods only remove nil values, not other falsey values like false or empty strings.