Predicate Method in Ruby: Definition and Usage Explained
predicate method is a method that ends with a question mark (?) and returns a boolean value (true or false). It is used to ask a yes/no question about an object’s state or property.How It Works
A predicate method in Ruby is like asking a simple yes or no question about something. Imagine you want to check if a light is on or off. Instead of just getting a number or string, you want a clear answer: yes or no. In Ruby, methods that answer these questions end with a ? mark to show they return true or false.
When you call a predicate method, Ruby runs the code inside it and gives you back a boolean result. This helps your program make decisions based on conditions, like whether a user is logged in or if a number is even.
Example
def even?(number) number % 2 == 0 end puts even?(4) # true puts even?(7) # false
When to Use
Use predicate methods whenever you want to check a condition and get a clear yes/no answer. They make your code easier to read because the ? at the end signals a true/false result.
Common real-world uses include checking if a string is empty, if a file exists, or if a user has permission. This helps keep your code clean and expressive.
Key Points
- Predicate methods always end with a
?to show they returntrueorfalse. - They help write clear and readable code by signaling a yes/no question.
- Common Ruby classes like
StringandArrayhave many built-in predicate methods.