Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is the difference between nil and false in Ruby?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring