From: Robert Klemme Date: 2010-10-13T18:18:45+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? On Wed, Oct 13, 2010 at 7:45 AM, Tony Arcieri wrote: > On Tue, Oct 12, 2010 at 6:39 AM, Rick DeNatale wrote: > >> Nobody seems to have mentioned it, I guess since this is the place for >> 'pure' rubyists, but Rails has the following methods: >> >> So with this you can write simply >> >>   var =  hash[key].try(:downcase) >> > > That's pretty cool, but I'd prefer it return a proxy object for all non-nil > objects that just relays the method call, and for nil a proxy that always > returns nil, ala: > > hash[key].try.downcase Like this? require 'singleton' class NilProxy include Singleton def method_missing(*a,&b) end end class Object def try self end end class NilClass def try NilProxy.instance end end ["Foo", nil, "Bar"].each do |x| p x.try.downcase end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/