From: Gary Wright Date: 2011-03-04T02:45:02+09:00 Subject: Re: How to assign an element to a hash only if its value is not nil? On Mar 3, 2011, at 12:10 PM, Thomas W. wrote: > Current solution is: > > hash[:key] = myvalue unless myvalue.nil? > > Is there something more beautiful? I tend to use #nil? and 'unless' sparingly and using them together like this makes my brain work to hard. Do you care specifically about distinguishing between nil and false? If not: hash[:key] = myvalue if myvalue would work. So would good old: if myvalue hash[:key] = myvalue end or maybe hash.store(key, myvalue) if myvalue if you don't like the look of the assignment. What is your default value for the hash? Do you need to avoid creating a key if myvalue is nil? If nil is your default value and you don't care about extra keys, then just do the assignment regardless of the value of myvalue. I would even suggest that you might want to arrange the rest of your code so that this is true. The idea is to work with the grain of Hash's normal behavior rather than fight against it. Gary Wright