How to use unless statement In Ruby

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


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