How to check if a variable is nil in Ruby?
In Ruby, nil is used to
indicate that a variable has not been assigned a value or that a method call returned nothing. This article focuses on discussing how to check if a variable is nil in Ruby.
Table of Content
- Using nil? method
- Using == operator
- Using unless statement
Using nil? method
The nil? method is used to explicitly check if a variable is nil
. It returns true
if the object isnil
, otherwise false
.
Syntax:
variable.nil?
Example:
Below is the Ruby program to check if a variable is nil using nil? method:
# Ruby program to check if a variable
# is nil using nil? method
# Example variable
variable = nil
if variable.nil?
puts "Variable is nil"
else
puts "Variable is not nil"
end
Output
Variable is nil
Explanation:
In this example, we use the nil?
method to explicitly check if the variable
is nil
. If variable
is nil
, it prints “Variable is nil”, otherwise “Variable is not nil”.
Using == operator
The ==
operator is used to compare a variable with nil
. It returns true
if the variable is nil
, otherwise false
.
Syntax:
variable == nil
Example:
Below is the Ruby program to check if a variable is nil using == operator.
# Ruby program to check if a variable
# is nil using == operator
# Example variable
variable = nil
if variable == nil
puts "Variable is nil"
else
puts "Variable is not nil"
end
Output
Variable is nil
Explanation:
In this example, the ==
operator compares variable
with nil
. If variable
is equal to nil
, it prints “Variable is nil”, otherwise “Variable is not nil”.
Using unless statement
The unless
statement is the opposite of the if
statement. It executes a block of code if the condition evaluates to false
or nil
.
Syntax:
unless variable
# Code to execute if variable is nil
end
Example:
Below is the Ruby program to check if a variable is nil using unless statement:
# Ruby program to check if a variable
# is nil using unless statement
# Example variable
variable = nil
unless variable
puts "Variable is nil"
else
puts "Variable is not nil"
end
Output
Variable is nil
Explanation:
In this example we use unless
statement to execute a block of code if variable
evaluates to false
or nil
. If variable
is nil
, it prints “Variable is nil”, otherwise “Variable is not nil”.
Contact Us