Not assigning nil values to a hash Not assigning nil values to a hash ruby-on-rails ruby-on-rails

Not assigning nil values to a hash


a little bit shorter if you negate the "unless" statement

hash1[:key] = hash2[:key] if hash2[:key]   # same as   if ! hash2[:key].nil?

you could also do the comparison in a && statement as suggested in other answers by Michael or Marc-Andre

It's really up to you, what you feel is most readable for you. By design, there are always multiple ways in Ruby to solve a problem.

You could also modify the hash2 :

hash1 = hash2.reject{|k,v| v.nil?}hash2.reject!{|k,v| v.nil?}   # even shorter, if in-place editing of hash2

this would remove key/value pairs :key => nil from hash2 (in place, if you use reject! )


I like this the best, loop and conditional overriding all in one line!

h1 = {:foo => 'foo', :bar => 'bar'}h2 = {:foo => 'oof', :bar => nil}h1.merge!(h2) { |key, old_val, new_val| new_val.nil? ? old_val : new_val }#=> {:foo => 'oof', :bar => 'bar'}

This will replace every value in h1 with the value of h2 where the keys are the same and the h2 value is not nil.


I'm not sure if that's really any better, but

hash2[:key] && hash[:key] = hash2[:key]

could work. Note that this would behave the same way for false and nil, if that's not what you want

!hash2[:key].nil? && hash[:key] = hash2[:key]

would be better. All of this assuming that :key would be an arbitrary value that you may not have control over.