Is nil the Same as false in Ruby?

In Ruby, nil and false are not the same:

  • nil is a special value in Ruby that represents "nothingness" or "absence of a value", such as when a variable has not yet been assigned a value;
  • false is a boolean value that represents a negative or failed condition.

Although, nil and false are both considered "falsy" values (meaning that they evaluate to false in a boolean context), still they are not the same thing.

For example, compare the two in a boolean context, where both evaluate to boolean false:

my_obj = nil

if my_obj
  puts "this will not be printed"
else
  puts "this will be printed"
end

#=> "this will be printed"
my_obj = false

if my_obj
  puts "this will not be printed"
else
  puts "this will be printed"
end

#=> "this will be printed"

However, they're two distinct values that do not equal to each other:

puts nil.class.name #=> NilClass
puts false.class.name #=> FalseClass

puts false == nil #=> false

It is important to note that nil and false are not interchangeable. They have different meanings and uses, and should be used appropriately in different contexts.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.