From: Steve Howell Date: 2010-03-30T13:35:10+09:00 Subject: coercing nil/obj to false/true I know this probably comes up a lot, but I could not Google the exact question as I'm formulating it. 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 The above code tersely coerces a result to a boolean value, but it's hard to read, because it's a double negative, and the "!" negative is lexically separated from the "nil?" negative. I occasionally do this instead: x = some_call_to_lib_that_returns_object_or_nil x.nil? That's more readable for me, but more verbose, and I can never decide what to name "x." I can add something like this to my codebase, but I'm wondering if something similar is already built in: def to_boolean x return !x.nil? end def is_there_an_x_like(whatever) to_boolean(some_call_to_lib_x_that_returns_object_or_nil(whatever)) end def is_there_a_y_like(whatever) to_boolean(some_call_to_y_lib_that_returns_object_or_nil(whatever)) 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.) Thoughts?