...

/

Predicates

Predicates

This lesson briefs the predicate methods in Ruby and how to use them.

Predicate Methods

If you check the list of methods on our String above you see that in Ruby we can have methods that end with a question mark ?. What’s up with that?

By convention, in Ruby, these methods return either true or false. For example, we can ask a number if it is even or odd:

$ irb
> 5.odd?
=> true

> 5.even?
=> false
Press + to interact
Ruby
puts 5.odd?
puts 5.even?

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

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

> 5.between?(1, 10)
=> true

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

These methods are called predicate methods in Ruby. Not quite sure why, maybe because of the historical math context of programming.

💡

Predicate methods that end with a question mark ? return either true or false.

Strings also define some predicate methods:

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

Do you also think it’s kinda odd that name.start_with?("a") reads almost like English, but not quite? Maybe the method could have been named starts_with? instead, right? That’s true. This is because Matz, the creator of Ruby, is not a native English speaker, and some names sound right in Japanese when translated literally.

Also:

> name = "Ruby Monstas"
> name.include?("by")
=> true

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

When we check what methods there are defined on a number, we find some with the same name, but also different ones:

$ irb
> 1.methods.sort
=> [:*, :+, :-, :/, :between?, :even?, :odd?, :zero?]
Press + to interact
Ruby
print 1.methods.sort

Let’s try zero?:

> 0.zero?
=> true

> 1.zero?
=> false
Press + to interact
Ruby
puts 0.zero?
puts 1.zero?

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

> [1, 2].include?(1)
=> true

> [1, 2].include?(3)
=> false

> { "eins" => "one" }.key?("eins")
=> true

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

Oh by the way, if you’re curious why operators like *, +, - and so on are also listed here, check the chapter that explains that operators are methods, too.

Access this course and 1200+ top-rated courses and projects.