Before you go, check out these stories!

Hackernoon logoUnderstanding Boolean Methods in Ruby With Examples by@SELMAe33

Understanding Boolean Methods in Ruby With Examples

Author profile picture

@SELMAe33Selma Ndi (Data Girl)

Full Stack Developer

Most programming languages have a Data Type called “Boolean”. This is
a form of data with only two possible values (usually “true” and
“false”). The Ruby language however does not have a Boolean Data

Ruby has Boolean Methods, otherwise called Predicates or Query. These are methods that end with a question mark (?) . It will be worth noting that only "false" and "nil" values evaluate to false in Ruby.

Let's take the example of the all? Boolean method;

%w[ant bear cat].all? { |word| word.length >= 3 } #=> true
%w[ant bear cat].all? { |word| word.length >= 4 } #=> false
%w[ant bear cat].all?(/t/)                        #=> false
[1, 2i, 3.14].all?(Numeric)                       #=> true
[nil, true, 99].all?                              #=> false
[].all?                                           #=> true

The all? method passes each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } which will cause all? to return true when none of the collection members are false or nil.

If instead a pattern is supplied, the method returns whether pattern === element for every collection member.

It is a similar case with the any? method

%w[ant bear cat].any? { |word| word.length >= 3 } #=> true
%w[ant bear cat].any? { |word| word.length >= 4 } #=> true
%w[ant bear cat].any?(/d/)                        #=> false
[nil, true, 99].any?(Integer)                     #=> true
[nil, true, 99].any?                              #=> true
[].any?                                           #=> false

From the above examples, we can conclude that the question mark (?) at the end of the method is set when we have a method that returns Boolean values — ‘true’ or ‘false’.

Creating Boolean Methods

Apart from the Boolean methods provided by Ruby, you can as well create your own Boolean Methods.

For example;

def is_even?(x)
  (x % 2) == 0 

def is_odd?(x)
  (x % 2) == 1 

def multiples_of_five?(x)
 (x % 5) == 0

def less_than_three?(x)
  x < 3 

puts is_even?(2) 
puts is_even?(3) 
puts is_odd?(2) 
puts is_odd?(3) 
puts multiples_of_five?(3) 
puts multiples_of_five?(5) 
puts less_than_three?(2) 
puts less_than_three?(4) 

This will result in the following


To conclude, we have learnt that;

  1. Methods that end with the question mark (?) are called Boolean methods;
  2. Boolean methods must return true or false;
  3. You can create your own Boolean methods in Ruby


Join Hacker Noon

Create your free account to unlock your custom reading experience.