BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

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

This blog is part of our Ruby 2.4 series.

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

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

Active Support already has a solution for this in the form of Hash#compact and Hash#compact!.

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 itself, 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 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.

Prathamesh Sonpatki in Ruby 2.4
24, 2016

You might also like

Ruby 2.4 has optimized enumerable min max methods

CSV::Row#each etc. return enumerator when no block given

Ruby 2.4 DateTime#to_time & Time#to_time keeps info

Avoid exception for dup on Integer

Ruby 2.4 no exception for objects converted to IPAddr

Subscribe to our newsletter