From: "David A. Black" Date: 2010-08-19T06:17:02+09:00 Subject: Re: Check existence of object and it's property at the same time Hi -- On Thu, 19 Aug 2010, Cory Patterson wrote: > I run into this from time to time and I was wondering if there is a > cleaner way to do check that an object is not nil and also check a > property of that object. > > I want to do this: > > if !@member.nil? and @member.is_active? > ... do something ... > else > ... do something else ... > end > > But this obviously raises a no method error if @member is nil. It doesn't, actually, because if @member is nil, the "and" is short-circuited so the right-hand expression doesn't get evaluated: >> if !@member.nil? and @member.is_active?; end => nil >> @member => nil A somewhat more common way of doing this is: if @member && @member.is_active? ... end There's a difference, though, which is that "if @member" is false if @member is false, not just if @member is nil. I'm a big non-fan of tri-state booleans involving true/false/nil, so I try to avoid situations where I have to distinguish between nil and false for condition-testing purposes. 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