From: Charles Calvert Date: 2010-10-22T01:55:57+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? On Wed, 20 Oct 2010 22:04:49 -0700 (PDT), w_a_x_man wrote in <42ffdc06-8d05-473b-b271-c5457c67c281@w9g2000prc.googlegroups.com>: >On Oct 11, 3: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? >> > >var = (t = h[key] and t.upcase) or nil Using short circuit evaluation to avoid the call to upcase if h[key] is nil, check. >var = h[key].tap{|x| x ? x.upcase : nil} Unfortunately tap is Ruby 1.9, and as I said above, I'm using 1.8.7. Thanks for the answers. -- Charles Calvert Moderator - alt.computer.consultants.moderated Submission Address: accm@celticwolf.net Contact Address: accm_mod@celticwolf.net