David,

You are completely correct.  I guess that was a bad example.  So the 
order of the conditions is important:

>> if @member and @member.is_active?; end
=> nil
>> if @member.is_active? && @member; end
NoMethodError: undefined method `is_active?' for nil:NilClass

I could have sworn I ran into this somewhere and it didn't work as 
expected.

Thanks so much for the insight, it is good information to have.

Cory




David A. Black wrote:
> Hi --
> 
> On Thu, 19 Aug 2010, Cory Patterson wrote:
> 
>> 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

-- 
Posted via http://www.ruby-forum.com/.