From: Mike Moore Date: 2011-03-05T00:20:38+09:00 Subject: Re: How to assign an element to a hash only if its value is not nil? On Fri, Mar 4, 2011 at 3:05 AM, Robert Klemme wrote: > > If you want to clearly communicate the intent you can add a comment or > an assert statement to that effect.  First inserting something that is > removed later is totally backwards. I'm sure there are cases where removing values from a hash is appropriate. > Plus, you might remove more than > intended, e.g. if there are nil values inserted previously and you > only want to avoid inserting nils during _this_ method call. In that case where you don't want to remove all nil values from a hash you shouldn't call `delete_if { |k, v| v.nil? }` > So, your > proposed solution is less efficient and error prone.  Now how is that > beautiful? Ouch. So its ugly *AND* buggy... # Check for nil values on hash assignment # Assuming false is a valid value h = {} h[:one] = one if !one.nil? # local method h[:two] = some_obj.two_method if !some_obj.two_method.nil? tmp = expensive_format_three(some_obj, some_other_obj) h[:three] = tmp if !tmp.nil? h # Delete nil values after hash assignment h = { :one => one, # local method :two => some_obj.two_method, :three => expensive_format_three(some_obj, some_other_obj) }.delete_if { |k, v| v.nil? }