From: Dave Burt Date: 2005-06-13T21:20:31+09:00 Subject: Re: Only if the object exists "Gavin Kistner" wrote... > If I write code like this: > self.foo.bar if self.foo > then ruby runs the #foo method twice. (Javascript is the same way.) > > If #foo is a lengthy process which I know has no side-effects, this > is wasteful. But, I need to ensure that #foo didn't return nil. I > have (at least) three choices: > > if ( tmp=foo ) > puts tmp.bar > end > > ( tmp=foo ) && ( puts tmp.bar ) > > puts tmp.bar if ( tmp=foo ) > > ..except that the last doesn't work, if 'tmp' has not been > previously seen as a local variable. Unfortunately, that's the form > that I really think looks best. The following method was mentioned a while back, and is a solution to this problem. class NilClass def method_missing() nil end end Cheers, Dave