0
0
RubyConceptBeginner · 3 min read

Predicate Method in Ruby: Definition and Usage Explained

In Ruby, a 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

Here is a simple example of a predicate method that checks if a number is even.
ruby
def even?(number)
  number % 2 == 0
end

puts even?(4)  # true
puts even?(7)  # false
Output
true 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 return true or false.
  • They help write clear and readable code by signaling a yes/no question.
  • Common Ruby classes like String and Array have many built-in predicate methods.

Key Takeaways

Predicate methods in Ruby end with a question mark and return true or false.
They make code easier to understand by clearly indicating a yes/no check.
Use predicate methods to ask about an object's state or condition.
Ruby's built-in classes include many useful predicate methods.
Naming predicate methods with a '?' is a Ruby convention for clarity.