Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove hash keys which hash value is blank?

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?

like image 521
user502052 Avatar asked Oct 02 '13 23:10

user502052


2 Answers

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 == '' }
like image 59
techvineet Avatar answered Oct 05 '22 16:10

techvineet


There are a number of ways to accomplish this common task

reject

This is the one I use most often for cleaning up hashes as its short, clean, and flexible enough to support any conditional and doesn't mutate the original object. Here is a good article on the benefits of immutability in ruby.

hash.reject {|_,v| v.blank?}

Note: The underscore in the above example is used to indicate that we want to unpack the tuple passed to the proc, but we aren't using the first value (key).

reject!

However, if you want to mutate the original object:

hash.reject! {|_,v| v.blank?}

select

Conversely, you use select which will only return the values that return true when evaluated

hash.select {|_,v| v.present? }

select!

...and the mutating version

hash.select {|_,v| v.present? }

compact

Lastly, when you only need to remove keys that have nil values...

hash.compact

compact!

You have picked up the pattern by now, but this is the version that modifies the original hash!

hash.compact!
like image 22
Will Bryant Avatar answered Oct 05 '22 15:10

Will Bryant