0
0
Rubyprogramming~5 mins

Predicate methods (ending with ?) in Ruby

Choose your learning style9 modes available
Introduction

Predicate methods help you check if something is true or false in a simple way. They make your code easier to read and understand.

When you want to check if a number is even or odd.
When you want to see if a string is empty.
When you want to find out if an object is nil (nothing).
When you want to check if a file exists.
When you want to test if a condition is true or false before doing something.
Syntax
Ruby
def method_name?
  # return true or false
end

Predicate methods always end with a question mark ?.

They return true or false to answer yes/no questions.

Examples
This method checks if a number is even. It returns true if yes, false if no.
Ruby
def even?(number)
  number % 2 == 0
end
The empty? method checks if a string has no characters.
Ruby
"hello".empty? # returns false
"".empty?      # returns true
The nil? method checks if an object is nil (nothing).
Ruby
object.nil? # returns true if object is nil
Sample Program

This program defines a predicate method positive? that checks if a number is greater than zero. It prints true or false based on the input.

Ruby
def positive?(number)
  number > 0
end

puts positive?(5)   # true
puts positive?(-3)  # false
puts positive?(0)   # false
OutputSuccess
Important Notes

Predicate methods should never change the object they check; they only answer yes/no questions.

Use predicate methods to make your code more readable and expressive.

Summary

Predicate methods end with a ? and return true or false.

They help check conditions clearly and simply.

Use them to ask yes/no questions about data or objects.