From: Mike Moore Date: 2011-03-04T02:38:45+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: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}