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?
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 == '' }
There are a number of ways to accomplish this common task
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).
However, if you want to mutate the original object:
hash.reject! {|_,v| v.blank?}
Conversely, you use select which will only return the values that return true when evaluated
hash.select {|_,v| v.present? }
...and the mutating version
hash.select {|_,v| v.present? }
Lastly, when you only need to remove keys that have nil
values...
hash.compact
You have picked up the pattern by now, but this is the version that modifies the original hash!
hash.compact!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With