From: Josh Cheek Date: 2010-10-12T05:19:00+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? --0016363b9f7ef29e9204925d1173 Content-Type: text/plain; charset=ISO-8859-1 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? > > -- > Charles Calvert > Moderator - alt.computer.consultants.moderated > Submission Address: accm@celticwolf.net > Contact Address: accm_mod@celticwolf.net > > I usually do: hash = { :key1 => nil , :key2 => "aBcD" } var = hash[:key1] && hash[:key1].downcase var # => nil var = hash[:key2] && hash[:key2].downcase var # => "abcd" Notice the nuance that if hash[:key1] is false, that will be assigned to var. 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? --0016363b9f7ef29e9204925d1173--