What is the difference between nil and false in Ruby?

Overview

Everything is regarded as an object in Ruby. Ruby’s built-in data types are false and nil.

nil

false

nil is a NilClass object

false is a FalseClass object

nil is not a valid value

false is a valid value

nil does have a type

false is a boolean data type

Pictorial representation of nil and false in Ruby

Note: In Ruby, true, false, and nil refer to objects rather than integers. The true and false are not the same as 0, and true and nil are not the same as 1.

Special case

When Ruby needs a boolean value, nil is treated as false, and values other than nil or false are treated as true.

students = ["Jeery", "Tom", "Eddie"]
#this will print student at index 0
puts students[0]
#nil
#this will output nothing since index doesnot exist
puts students[4]
#this will output the class that belongs to nil
puts students[4].class
#false
#this will output false since both names does not match
puts students[0] == students[1]
#this will output the class that belongs to false
puts (students[0] == students[1]).class
#special case
#nil treated as false
Jeery = nil
if Jeery
puts "Jeery is present"
else
puts "Jeery is absent"
end
#false treated as false
Tom = false
if Tom
puts "Tom is present"
else
puts "Tom is absent"
end

Explanation

  • Line 4: We print the student at index 0.
  • Line 6–10: We print the nil and nil class.
  • Line 12–16: We print the false and false class.
  • Line 19–34: We print the special case, when the nil is also treated as false followed by the behavior of actual false.

Free Resources