How to use nil? method In Ruby
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”.
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
Contact Us