On Mar 30, 12:17     
> 2010/3/30 Steve Howell <showel... / yahoo.com>:
>
> > Is there a way to avoid this idiom?
>
> > def is_there_one(whatever)
> > some_call_to_lib_that_returns_object_or_nil(whatever).nil?
> > end
> > Finally, I can just have my method return obj or nil, and let the
> > callers use it in boolean expressions, but my fear there is that I set
> > the wrong expectation for the caller, if I later return a different
> > object, when my intention is only to indicate whether a query succeeds
> > or not. You guessed it, this is motivated by ActiveRecord, but it's
> > really a Ruby question.)
>
> Your method's documentation and naming the method with a question mark
> at the end will help avoid this.     
> leaking internal information. 
Yep.

> That's why people often do this in
> order to force conversion to true / false:
>
> def is_there_one? whatever
> !! some_call_to_lib_that_returns_object_or_nil(whatever)
> end
>

Ok, thanks, I find that more readable than !foo.nil?.

> If the call is expensive then I'd just return whatever is found and
> let the caller check for nil in one of the many ways.
>
> Btw, databases typically return always a collection - albeit it might
> be empty.      
> course.
>

Yep, understood, but ActiveRecord returns nil or object when you pass
find the :first parameter.  It's useful in some situations where you
just want to check that a record has at least one active child,
without caring about the children themselves, such as when you are
cleaning up "parent" objects that have been orphaned.