From: Charles Calvert Date: 2010-10-21T01:35:13+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? On Wed, 13 Oct 2010 22:11:17 -0700 (PDT), Steve Howell wrote in : >On Oct 11, 1:02�pm, Charles Calvert wrote: >> I'm using Ruby 1.8.7 patchlevel 249 >> >> Is there a more idiomatic way to do the following? >> >> var = hash[key].nil? ? nil : hash[key].downcase >> >> Note that if hash[key] is nil, I want nil assigned to var, so this >> won't work: >> >> var = hash[key].downcase unless hash[key].nil? >> >> Obviously I could do this, but I'm trying to keep it on one line: >> >> var = hash[key] >> var = var.downcase unless var.nil? >> > >I'm not sure if this is the most common idiom, but you can write a >helper method like "try" that chains method calls but aborts nicely to >nil as soon as an object dereference (or the primary object itself) >evaluates to nil. [snip example] I was looking for something that didn't require patching existing classes, but it's becoming clearer to me that such patches are much more common than I thought and can yield cleaner code. Thanks for the example. -- Charles Calvert Moderator - alt.computer.consultants.moderated Submission Address: accm@celticwolf.net Contact Address: accm_mod@celticwolf.net