0
0
Rubyprogramming~3 mins

Why Predicate methods (ending with ?) in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could ask questions in your code as simply as you ask a friend?

The Scenario

Imagine you want to check if a user is logged in or if a number is even by writing long if-else statements everywhere in your code.

You have to write full checks like if user.logged_in == true or if number % 2 == 0 repeatedly.

The Problem

This manual way is slow and makes your code bulky and hard to read.

It's easy to make mistakes, like forgetting to compare properly or mixing up true/false values.

It also makes your code less clear about what you are really checking.

The Solution

Predicate methods ending with ? give you a simple, clear way to ask yes/no questions in your code.

They return true or false directly, so you can write user.logged_in? or number.even? and instantly understand the check.

Before vs After
Before
if user.logged_in == true
  puts 'Welcome!'
end
After
if user.logged_in?
  puts 'Welcome!'
end
What It Enables

It makes your code cleaner, easier to read, and less error-prone by clearly expressing yes/no questions.

Real Life Example

When building a website, you can quickly check if a user is an admin by calling user.admin? instead of writing complex checks.

Key Takeaways

Predicate methods end with ? and return true or false.

They simplify yes/no checks in your code.

Using them makes your code easier to read and less error-prone.