Reason #168 •
June 17th, 2026
Getting rid of nils with #compact
Methods that seem to come in handy more often than not are Ruby's various #compact methods, which remove nil values from collections:
Ruby
array = [1, nil, 2, nil, 3]
array.compact
# => [1, 2, 3]
hash = { a: 1, b: nil, c: 2, d: nil, e: 3 }
hash.compact
# => { a: 1, c: 2, e: 3 }
JavaScript
const array = [1, null, 2, null, 3];
array.filter(x => x !== null);
// => [1, 2, 3]
const hash = { a: 1, b: null, c: 2, d: null, e: 3 };
Object.fromEntries(
Object.entries(hash).filter(([_, v]) => v !== null)
);
// => { a: 1, c: 2, e: 3 }
One might say that the Ruby version is more compact than the comparison, and so much nicer for it!
History
Array#compact has been part of Ruby since its inception.
Hash#compact was added in Ruby 2.4.0, released on December 24, 2016. The implementation was explicitly added to port the existing ActiveSupport behavior into Ruby itself, which is why Rails developers may have met this method before it became part of core Ruby.
Enumerable#compact arrived later in Ruby 3.1.0, released on Christmas 2021.