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
# 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

Similar Reads

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....

Using == operator

The == operator is used to compare a variable with nil. It returns true if the variable is nil, otherwise false....

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....

Contact Us