Predicate Methods

Learn about the predicate methods in Ruby and how to use them.

We'll cover the following

Predicate methods

If we look at the list of methods defined for a String object, we see that there are methods that end with a question mark (?).

In Ruby convention, these methods return either true or false. For example, we can ask a number if it’s even or odd:

Press + to interact
puts 5.odd?
puts 5.even?

This makes them read like a question, which is pretty cool.

We can also ask the number if it’s between two other numbers. This method needs us to pass those two other numbers. So, we now also have an example of a method that takes two arguments:

Press + to interact
puts 5.between?(1, 10)
puts 5.between?(11, 20)

These are called predicate methods in Ruby, likely because of the historical math context of programming.

Remember: Predicate methods that end with a question mark (?) return either true or false.

Strings also define some predicate methods:

Press + to interact
name = "Ruby Monstas"
puts name.start_with?("R")
puts name.start_with?("a")

It might also seem strange that name.start_with?("a") reads almost like an English sentence. Perhaps the method could have been named starts_with? instead? That’s true. This is because Matz, the creator of Ruby, isn’t a native English speaker, and some names sound right in Japanese when translated literally.

Press + to interact
name = "Ruby Monstas"
puts name.include?("by")
puts name.include?("r")

Arrays have the include? methods, and hashes respond to key?:

Press + to interact
puts [1, 2].include?(1)
puts [1, 2].include?(3)
puts ({ "eins"=>"one" }.key?("eins"))
puts ({ "eins" => "one" }.key?("zwei"))

When we check what methods are defined on a number, we find some interesting ones:

Press + to interact
print 1.methods.sort

Let’s try zero?:

Press + to interact
puts 0.zero?
puts 1.zero?

The *, +, and - operators might be surprising to see here, but we’ll soon see that operators are methods too.