From: "David A. Black" Date: 2010-10-12T06:33:22+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? Hi -- On Tue, 12 Oct 2010, 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? It actually will work if var has not been initialized before. But that's more or less an artifact of how the parser treats local variable assignment expressions, and is pretty fragile: >> hash = {} => {} >> var = hash[1].downcase unless hash[1].nil? => nil >> var => nil >> var2 = "something" => "something" >> var2 = hash[1].downcase unless hash[1].nil? => nil >> var2 => "something" David -- David A. Black, Senior Developer, Cyrus Innovation Inc. The Ruby training with Black/Brown/McAnally Compleat Philadelphia, PA, October 1-2, 2010 Rubyist http://www.compleatrubyist.com