Predicates represent a single argument methods that return either true
or false
. It’s not supposed to preform any additional actions or change anything. In Ruby, there is a naming convention where predicate methods are followed by a question mark at the end of the method name. In other words, when you see the question mark at the end, you can easily assume what are the possible return values.
Here are a few basic examples:
> 5.even?
=> false
> 1.zero?
=> false
> -1.positive?
=> false
When you define a new method in your code and it returns only true
or false
, make sure to add a question mark at the end to follow the convention and to make the code easier to read for others.
# Bad - missing question mark
class Integer
def is_star
self == 5
end
end
# Good
class Integer
def star?
self == 5
end
end
# Bad - should return only true or false
def admin?
current_admin
end
# Good
def admin?
current_admin.present?
end