How to remove hash keys which hash value is blank?

user502052 picture user502052 · Oct 3, 2013 · Viewed 18k times · Source

I am using Ruby on Rails 3.2.13 and I would like to remove hash keys which corresponding hash value is blank. That is, if I have the following hash

{ :a => 0, :b => 1, :c => true, :d => "", :e => "   ", :f => nil }

then the resulting hash should be (note: 0 and true are not considered blank)

{ :a => 0, :b => 1, :c => true }

How can I make that?

Answer

techvineet picture techvineet · Oct 3, 2013

If using Rails you can try

hash.delete_if { |key, value| value.blank? }

or in case of just Ruby

hash.delete_if { |key, value| value.to_s.strip == '' }