In Ruby, you can check if an object is nil
by using the NilClass#nil?
method, which returns a boolean true
only if the object is nil
, and false
otherwise:
puts nil.nil? #=> true puts "foo".nil? #=> false puts false.nil? #=> false puts 0.nil? #=> false # ...
For example:
my_obj = nil if my_obj.nil? puts "object is nil" else puts "object is not nil" end #=> "object is nil"
This will output "object is nil
" because my_obj
is nil
.
As an alternative, you can also use the ==
operator to check if an object is equal to nil
:
my_obj = nil if my_obj == nil puts "object is nil" else puts "object is not nil" end #=> "object is nil"
This will also output "object is nil
". However, it's more idiomatic to use the NilClass#nil?
method when checking for nil
in Ruby.
This post was published 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.