From: Charles Calvert Date: 2010-10-14T02:30:22+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? On Mon, 11 Oct 2010 23:04:59 -0500, Joel VanderWerf wrote in <4CB3DE66.3040006@gmail.com>: >On 10/11/2010 08:44 PM, Charles Calvert wrote: >> On Mon, 11 Oct 2010 22:01:43 -0500, "ara.t.howard" >> wrote in >> <0b78a0a6-c2f2-4321-92bc-d7e6acc5c869@d25g2000yqc.googlegroups.com>: >> >>> >>> var = hash[key].downcase if hash[key] >> >> This is a variant of: >> >> var = hash[key].downcase unless hash[key].nil? >> >> which I indicated in my original post won't work, as I want an >> explicit assignment of nil to var in the event that hash[key] returns >> nil. See David Black's response to my post. I'm not assuming that >> this is the first occurrence of var, so it may already have a value >> from a previous assignment. > >You can get around this by putting ( ) around the whole if clause: > >var = (hash[key].downcase if hash[key]) > >It works because (... if ...) returns nil if the condition is false. While that would clearly work, it makes me a little nervous as it isn't immediately obvious, to me at least. Most likely I just haven't spent enough time with Ruby. :) -- Charles Calvert Moderator - alt.computer.consultants.moderated Submission Address: accm@celticwolf.net Contact Address: accm_mod@celticwolf.net