Not assigning nil values to a hash

Red picture Red · Nov 29, 2011 · Viewed 20.1k times · Source

Is there a short hand or best practice for assigning things to a hash when they are nil in ruby? For example, my problem is that I am using another hash to build this and if something in it is nil, it assigns nil to that key, rather than just leaving it alone. I understand why this happens so my solution was:

hash1[:key] = hash2[:key] unless hash2[:key].nil?

Because I cannot have a value in the has where the key actually points to nil. (I would rather have an empty hash than one that has {:key => nil}, that can't happen)

My question would be is there a better way to do this? I don't want to do a delete_if at the end of the assignments.

Answer

Tilo picture Tilo · Nov 30, 2011

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! )