user502052
user502052

Reputation: 15257

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?

Upvotes: 23

Views: 22012

Answers (3)

user2069311
user2069311

Reputation: 144

With respect to techvineet's solution, note the following when value == [].

[].blank?               => true 
[].to_s.strip == ''     => false 
[].to_s.strip.empty?    => false

Upvotes: 0

Will Bryant
Will Bryant

Reputation: 343

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!

Upvotes: 21

techvineet
techvineet

Reputation: 5111

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 == '' }

Upvotes: 34

Related Questions