From: Charles Calvert Date: 2010-10-12T12:25:11+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? On Mon, 11 Oct 2010 15:19:00 -0500, Josh Cheek wrote in : >[Note: parts of this message were removed to make it a legal post.] > >On Mon, Oct 11, 2010 at 3:05 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 usually do: >hash = { :key1 => nil , :key2 => "aBcD" } > >var = hash[:key1] && hash[:key1].downcase >var # => nil > >var = hash[:key2] && hash[:key2].downcase >var # => "abcd" Using the short-circuit evaluation of && to avoid calling downcase. Interesting. >Notice the nuance that if hash[:key1] is false, that will be assigned to >var. Yes, that's a weakness of the technique, though it wouldn't matter in the use case at hand. >This also works: > >var = hash[:key1].downcase rescue nil >var # => nil > >var = hash[:key2].downcase rescue nil >var # => "abcd" > >But people seem to really be opposed to doing this. Not entirely sure why. >Maybe because it wouldn't raise an error if, for example, you put some >absurd type of data in your hash? I don't have enough experience with exception handling in Ruby to know for sure, but I suspect that it's considered a bad practice because it might accidentally catch exceptions other than the intended one. It's being discussed in another subthread, so I'll watch that. -- Charles Calvert Moderator - alt.computer.consultants.moderated Submission Address: accm@celticwolf.net Contact Address: accm_mod@celticwolf.net