From: Robert Klemme Date: 2011-03-04T02:55:23+09:00 Subject: Re: How to assign an element to a hash only if its value is not nil? 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. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/