DEV Community

Cover image for Ruby Predicate Methods
Shaher Shamroukh
Shaher Shamroukh

Posted on

Ruby Predicate Methods

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
Enter fullscreen mode Exit fullscreen mode

.even?

5.even?
false
Enter fullscreen mode Exit fullscreen mode

.between?

7.between?(1, 9)
true

11.between?(1, 9)
false
Enter fullscreen mode Exit fullscreen mode

.zero?

2.zero?
false

0.zero?
true
Enter fullscreen mode Exit fullscreen mode

.include?

[1, 2, 3].include?(3)
true

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

"Hello Ruby".include?("by")
true

"Hello Ruby".include?("m")
false
Enter fullscreen mode Exit fullscreen mode

.key? & .value?

{ num: 9 }.key?(:wrong)
false

{ str: "Hello" }.value?("Hello")
true
Enter fullscreen mode Exit fullscreen mode

.has_key? & .has_value?

{ num1: 9, num2: 7 }.has_key?(:num2)
true

{ lang1: "Ruby", lang2: "JavaScript" }.has_value?("Python")
false
Enter fullscreen mode Exit fullscreen mode

.start_with? & it's opposite .end_with?

"Hello Ruby".start_with?("by")
false

"Hello Ruby".end_with?("by")
true
Enter fullscreen mode Exit fullscreen mode

.is_a?

4.is_a? String
false

"Hello".is_a? String
true
Enter fullscreen mode Exit fullscreen mode

.empty?

[].empty?
true

[1, 2].empty?
false
Enter fullscreen mode Exit fullscreen mode

These ones are the handiest ruby predicate methods and still, there are more please visit Ruby-Docs to see the whole list.

Top comments (0)