True, False and Nil in Ruby Programming


We know that everything in Ruby is treated as an object, and so the true, false and nil as well. They are built-in types that Ruby provides to do different conditional checks and more. In this article, we will explore different examples of the true, false and nil data types and how to use them.

True, False in Ruby

Let's start with a very simple example where we will check if two variables are equal or not.

Example 1

Consider the code shown below

first = 10
second = 10

if first == second
   # If Condition is true
   puts "True! First and second are equal"

else
   # If Condition is false
   puts "False! First and second are not equal"

end

Output

It will generate the following output −

True! First and second are equal

Example 2

Let's consider another example of True, False. Here, we will compare two strings.

a1 = "The quick brown fox jumps over the lazy dog."
b1 = "The quick brown fox jumps over the lazy dog."
result1 = a1 == b1

puts result1

a2 = "An apple a day keeps the doctor away."
b2 = "An orange a day keeps the doctor away."
result2 = a2 == b2

puts result2

Output

It will generate the following output −

true
false

Nil in Ruby

Now that we have some idea about how to make use of the True, False built-in types in Ruby, let's explore some code examples of Nil as well.

Example 3

Consider the code shown below

arr = [ 1, 2, 3, 4, 5 ]

# Since arr[5] does not exist, it is nil.
res1 = arr[5].nil?
puts res1

# Since arr[2] exists, it is not nil.
res2 = arr[2].nil?
puts res2

Output

It will generate the following output −

true
false

Updated on: 25-Jan-2022

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements