What is a predicate in the context of Ruby method naming conventions?
What is a predicate in the context of Ruby method naming conventions?
In the context of Ruby method naming conventions, a predicate is a method that returns a boolean value, indicating whether a certain condition is true or false. These methods are easily identifiable by the question mark ?
at the end of their names. The use of a question mark is a Ruby-specific convention that signals to the reader that the method will return a boolean-like value, which can be either true
, false
, or a truthy or falsy value in Ruby terms[3][4].
Predicate methods are intended to be simple queries about the state of an object and should not produce side effects. This means that calling a predicate method should not alter the state of the object or have any other side effects; it should only return information about the object's state[3][4].
For example, consider the following Ruby methods:
def empty?
# returns true if a collection is empty
end
def valid?
# returns true if an object meets certain validation criteria
end
In these examples, empty?
and valid?
are predicate methods...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào