From: Mike Moore Date: 2011-03-04T03:27:29+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 10:55 AM, Robert Klemme wrote: > On 03.03.2011 18:38, Mike Moore wrote: >> >> On Thu, Mar 3, 2011 at 10:10 AM, Thomas W.  wrote: >>> >>> hash = {} >>>    hash[:key] = myvalue >>> >>> >>> How to assign hash[:key] only if myvalue is not nil? >>> >>> Current solution is: >>> >>>    hash[:key] = myvalue unless myvalue.nil? >>> >>> >>> Is there something more beautiful? >> >> 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.