From: Robert Klemme Date: 2011-03-04T19:05:57+09:00 Subject: Re: How to assign an element to a hash only if its value is not nil? On Thu, Mar 3, 2011 at 7:27 PM, Mike Moore wrote: > On Thu, Mar 3, 2011 at 10:55 AM, Robert Klemme > wrote: >> On 03.03.2011 18:38, Mike Moore wrote: >>> You could assign the all values and then remove the just the nil >>> values afterward. >>> >>>   >>  h = { :one =>  1, :two =>  2, :three =>  nil, :four =>  4, :five => >>>  nil } >>>   =>  {:three=>nil, :four=>4, :five=>nil, :one=>1, :two=>2} >>>   >>  h[:six] = 6 >>>   =>  6 >>>   >>  h[:seven] = nil >>>   =>  nil >>>   >>  h.delete_if { |k, v| v.nil? } >>>   =>  {:four=>4, :six=>6, :one=>1, :two=>2} >> >> Oh, this is so ugly.  And also potentially inefficient since the hash table >> might grow larger than needed. > > I disagree. I think removing nil values afterwards is nicer (more > beautiful?) than having the check on every single assignment. And this > isn't likely to be your bottleneck so trading a little inefficiency is > worthy of clearly communicating your intent, IMO. 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. 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. So, your proposed solution is less efficient and error prone. Now how is that beautiful? Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/