2010/3/30 Steve Howell <showell30 / 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.  I would be more concerned with
leaking internal information.  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

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.  That depends on your mechanics in the invoked method of
course.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/