---
title: "Hash#compact and Hash#compact! now part of Ruby 2.4"
description:
  "Ruby 2.4 has added Hash#compact and Hash#compact! methods into core"
canonical_url: "https://www.bigbinary.com/blog/hash-compact-and-hash-compact-now-part-of-ruby-2-4"
markdown_url: "https://www.bigbinary.com/blog/hash-compact-and-hash-compact-now-part-of-ruby-2-4.md"
---

# Hash#compact and Hash#compact! now part of Ruby 2.4

Ruby 2.4 has added Hash#compact and Hash#compact! methods into core

- Author: Prathamesh Sonpatki
- Published: October 24, 2016
- Categories: Ruby 2.4, Ruby

It is a common use case to remove the `nil` values from a hash in Ruby.

```ruby
{ "name" => "prathamesh", "email" => nil} => { "name" => "prathamesh" }
```

Active Support already has a solution for this in the form of
[Hash#compact](http://api.rubyonrails.org/classes/Hash.html#method-i-compact)
and
[Hash#compact!](http://api.rubyonrails.org/classes/Hash.html#method-i-compact-21).

```ruby
hash = { "name" => "prathamesh", "email" => nil}
hash.compact #=> { "name" => "prathamesh" }
hash #=> { "name" => "prathamesh", "email" => nil}

hash.compact! #=> { "name" => "prathamesh" }
hash #=> { "name" => "prathamesh" }
```

Now, Ruby 2.4 will have these 2 methods in the
[language](https://bugs.ruby-lang.org/issues/11818)
[itself](https://bugs.ruby-lang.org/issues/12863), so even those not using Rails
or Active Support will be able to use them. Additionally it will also give
performance boost over the Active Support versions because now these methods are
implemented in C natively whereas the Active Support versions are in Ruby.

There is already a
[pull request open](https://github.com/rails/rails/pull/26868) in Rails to use
the native versions of these methods from Ruby 2.4 whenever available so that we
will be able to use the performance boost.

## Links

- [Human page](https://www.bigbinary.com/blog/hash-compact-and-hash-compact-now-part-of-ruby-2-4)
