From: Tony Arcieri Date: 2010-10-12T11:59:27+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? --001485f19ef49a4576049262a946 Content-Type: text/plain; charset=ISO-8859-1 Haskell solves the "may be nil" problem with the Maybe monad (from Haskell). There's many ways to implement something similar... such as implementing Object#maybe whose method_missing (e.g. Maybe#method_missing) proxies to the original object. NilClass can also implement #maybe, and always return nil. On Mon, Oct 11, 2010 at 2: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 > > -- Tony Arcieri Medioh! A Kudelski Brand --001485f19ef49a4576049262a946--