Should a method ending in ? (question mark) return only a boolean?

Adding a ? to the end of a method name does not in any way change the return value of the method, but instead only indicates that it is a predicate method. That is, that the method's return value should be treated as a boolean, but does not need to be strictly boolean (i.e. true or false).

Many of the other answers state that it should return a value that is truthy or falsy. This is rather redundant, since everything can be either truthy or falsy, and since all methods in Ruby return something (unless they raise an exception), the return value is always truthy or falsy.

Think of appending a ? as a nicer alternative to prepending is_ in other languages; e.g. I would either have subscribed? or is_subscribed.


A method ending with ? should return a value which can be evaluated to true or false. If you want to ensure a boolean return, you can do so by adding a double bang to the finder.

def is_subscribed?(feed_url)
  !!Subscription.find_by_user_id_and_feed_id(self[ :id ], Feed.find_by_feed_url(feed_url))
end

It should a 'truthy' or 'falsy' value, that can be used safely in predicates, but does not have to return literal true or false. There are even methods like this, like File.size?, in the standard library.

Tags:

Ruby