Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

True, False, and Nil In Ruby

  • Last Updated : 02 Sep, 2021

Ruby is an open-sourced object-oriented programming language developed by Yukihiro Matsumoto. In Ruby, everything is treated as an object. true, false and nil are built-in data types of Ruby. 
Note: Always remember in Ruby true, false, and nil are objects, not numbers. Whenever Ruby requires a Boolean value, then nil behaves like false and values other than nil or false behave like true.
 

True and False

In Ruby, true and false are boolean values that represent yes and no. true is an object of TrueClass and false is an object of FalseClass. 
Note: Ruby does not contain Boolean class. 
Let’s see a few examples of true and false in Ruby. 
Example 1: 
 

Ruby




# Ruby program to illustrate the use
# of true and false
a = 4
b = 4
 
if a == b
     
    # If Condition is true
    puts "True! a and b are equal"
     
else
     
    # If Condition is false
    puts "False! a and b are not equal"
     
end

Output: 
 

True! a and b are equal

Example 2: 
 

Ruby




# Ruby program to illustrate the use
# of true and false
a1 = "GeeksforGeeks"
b1 = "GeeksforGeeks"
result1 = a1 == b1
 
puts result1
 
a2 = "GeeksforGeeks"
b2 = "geeks"
result2 = a2 == b2
 
puts result2

Output: 
 

true
false

Example 3: 
 

Ruby




# Ruby program to illustrate the use
# of true and false
 
# If condition is true
if 55 == 55
 
  puts "GeeksforGeeks !"
 
# If Condition is false
else
  
  puts " A Computer Science Portal for Geeks!"
  
end

Output: 
 

GeeksforGeeks !

 

Nil

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby’s way of referring to nothing or void. Ruby also provide a nil? method to detect if any object is nil or not. 
Example 1: 
 

Ruby




# Checking for nil's class
a = nil.class
puts a

Output: 
 

 NilClass

Example 2: 
 

Ruby




# Ruby program to illustrate nil? method
# Checking for Nil
array = [ 1, 2, 3, 4, 5 ]
 
# Since array[5] does not exist so, it is nil.
result1 = array[5].nil?
puts result1
 
# Since array[2] exists so, it is not nil.
result2 = array[2].nil?
puts result2

Output: 
 

true
false

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!