Ruby Predicate Methods
Shaher Shamroukh
Posted on April 11, 2021
What is a predicate method?
A method that returns true or false is called a “predicate method”.
In Ruby, the naming convention for predicate methods ends with a question mark.
This improves readability by making Ruby code read more like English.
In this article, we are going to list the handiest predicate methods in ruby with examples.
.odd?
3.odd?
true
.even?
5.even?
false
.between?
7.between?(1, 9)
true
11.between?(1, 9)
false
.zero?
2.zero?
false
0.zero?
true
.include?
[1, 2, 3].include?(3)
true
[1, 2, 3].include?(4)
false
"Hello Ruby".include?("by")
true
"Hello Ruby".include?("m")
false
.key? & .value?
{ num: 9 }.key?(:wrong)
false
{ str: "Hello" }.value?("Hello")
true
.has_key? & .has_value?
{ num1: 9, num2: 7 }.has_key?(:num2)
true
{ lang1: "Ruby", lang2: "JavaScript" }.has_value?("Python")
false
.start_with? & it's opposite .end_with?
"Hello Ruby".start_with?("by")
false
"Hello Ruby".end_with?("by")
true
.is_a?
4.is_a? String
false
"Hello".is_a? String
true
.empty?
[].empty?
true
[1, 2].empty?
false
These ones are the handiest ruby predicate methods and still, there are more please visit Ruby-Docs to see the whole list.
💖 💪 🙅 🚩
Shaher Shamroukh
Posted on April 11, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.