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 withoutnilvalues.array.compact!- removesnilvalues from the same array and returns it, ornilif 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:
| Method | Description | Returns |
|---|---|---|
array.compact | Returns a new array without nil values | New array |
array.compact! | Removes nil values from the original array | Modified 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.