From: Rick DeNatale Date: 2010-10-12T21:39:56+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? On Mon, Oct 11, 2010 at 10:59 PM, Tony Arcieri wrote: > 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? >> Nobody seems to have mentioned it, I guess since this is the place for 'pure' rubyists, but Rails has the following methods: class Object def try(method, *args, &block) send(method, *args, &block) end end class NilClass def try(*args) nil end end So with this you can write simply var = hash[key].try(:downcase) -- Rick DeNatale Help fund my talk at Ruby Conf 2010:http://pledgie.com/campaigns/13677 Blog: http://talklikeaduck.denhaven2.com/ Github: http://github.com/rubyredrick Twitter: @RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale