× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Ruby: Removing all empty elements from a hash / YAML?

David Gil Pérez
Mar 04, 2015
<p>Rails 4.1 added <a href="http://api.rubyonrails.org/classes/Hash.html#method-i-compact" rel="nofollow">Hash#compact</a> and <a href="http://api.rubyonrails.org/classes/Hash.html#method-i-compact-21" rel="nofollow">Hash#compact!</a> as a core extensions to Ruby's <code>Hash</code> class. Yeah! You can use it like this:</p> <pre><code>hash = { a: true, b: false, c: nil} hash.compact # =&gt; { a: true, b: false} hash # =&gt; { a: true, b: false, c: nil} { c: nil }.compact # =&gt; {} </code></pre> <p>As a curiosity, they implemented it using <code>#select</code> instead of <code>#delete_if</code> for performance reasons. See <a href="https://gist.github.com/tinogomes/8332883" rel="nofollow">here for the benchmak</a>.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/3450641/Ruby:%20Removing%20all%20empty%20elements%20from%20a%20hash%20/%20YAML?/25463847">Stack Overflow</a>.</p>
comments powered by Disqus