0
0
Rubyprogramming~5 mins

Predicate methods (ending with ?) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a predicate method in Ruby?
A predicate method is a method that ends with a question mark (?) and returns a boolean value (true or false). It answers a yes/no question about an object.
Click to reveal answer
beginner
Why do predicate methods in Ruby end with a question mark (?)?
The question mark at the end signals that the method returns a boolean value, making it clear the method answers a yes/no question.
Click to reveal answer
beginner
Example: What does the Ruby method `empty?` do when called on an array?
The `empty?` method returns true if the array has no elements, otherwise it returns false.
Click to reveal answer
intermediate
How would you define a custom predicate method in Ruby?
Define a method ending with `?` that returns true or false based on a condition. For example:<br>
def adult?(age)
  age >= 18
end
Click to reveal answer
intermediate
Can predicate methods return values other than true or false?
Technically yes, but by convention predicate methods should return only true or false to clearly indicate a yes/no answer.
Click to reveal answer
What does a predicate method in Ruby always return?
Atrue or false
Ba string
Can integer
Dnil
Which of these is a valid predicate method name in Ruby?
Avalid?
Bcheck
Crun!
Dstart
What does the Ruby method `nil?` check?
AIf an object is empty
BIf an object is a number
CIf an object is true
DIf an object is nil
How do you call a predicate method named `empty?` on an array named `arr`?
Aarr.empty
Bempty?(arr)
Carr.empty?
Dempty.arr?
Why is it helpful to use predicate methods?
AThey speed up the program
BThey make code easier to read by clearly showing yes/no checks
CThey return strings
DThey create new objects
Explain what a predicate method is and why it ends with a question mark in Ruby.
Think about how Ruby shows methods that answer true or false questions.
You got /3 concepts.
    Write a simple custom predicate method in Ruby that checks if a number is even.
    Use the modulo operator (%) to check even numbers.
    You got /3 concepts.