Array#compact
arr.compact -> array Returns:
array · Updated March 13, 2026 · Array Methods arrays compact nil enumerable
Array#compact removes all nil values from an array and returns a new array. This is useful for cleaning up data after operations that may produce nil values, such as array indexing or mapping.
Syntax
arr.compact
arr.compact!
The method without a bang (compact) returns a new array. The bang version (compact!) modifies the array in place and returns the array itself.
Parameters
This method takes no parameters.
Examples
Basic usage
# Remove nil values from an array
array = [1, nil, 2, nil, 3]
array.compact
# => [1, 2, 3]
# Original array is unchanged
array
# => [1, nil, 2, nil, 3]
Destructive version
# compact! modifies in place
array = [1, nil, 2, nil, 3]
array.compact!
# => [1, 2, 3]
# Now the original is modified
array
# => [1, 2, 3]
With mixed values
# Works with any object types
data = ["hello", nil, 42, nil, :symbol, [1, 2], nil]
data.compact
# => ["hello", 42, :symbol, [1, 2]]
After mapping
# Common pattern: compact after map that can return nil
numbers = [1, 2, 3, 4, 5]
squared_evens = numbers.map { |n| n ** 2 if n.even? }
# => [nil, 4, nil, 16, nil]
squared_evens.compact
# => [4, 16]
Common Patterns
Cleaning database results
# Simulating database query results
users = [
{ name: "Alice", email: nil },
{ name: "Bob", email: "bob@example.com" },
{ name: nil, email: "charlie@example.com" }
]
users.map { |u| u[:email] }.compact
# => ["bob@example.com", "charlie@example.com"]
Filtering while preserving order
# Keep first non-nil value
values = [nil, nil, "found", nil]
values.compact.first
# => "found"
Error Cases
The method never raises an error. It works on any array:
# Empty array
[].compact
# => []
# Array with no nils
[1, 2, 3].compact
# => [1, 2, 3]
# All nils
[nil, nil].compact
# => []