Unless statement and Unless modifier in Ruby

RubyServer Side ProgrammingProgramming

Unless Statement

We know that we can use the if statement when we want to run some code based on a condition that evaluates to True. Ruby also provides a special statement known as unless statement that can be used to run some code based on the condition that evaluates to False.

It is quite the opposite of the if statement.

Syntax

The syntax of the unless statement is shown below.

unless condition
   # some code
else
   # some code
end

Now let's take a couple of examples to demonstrate how it works.

Example 1

Consider the code shown below

# unless statement example
num = 2

unless num > 1
   puts "num is less than 1"
else
   puts "num is greater than 1"
end

Output

num is greater than 1

Example 2

# unless statement example

num = 1

# clearly 1 is less than 4
unless num > 4
   # the below will get printed
   puts "TutorialsPoint!"
else
   puts "Oh no!"
end

Output

TutorialsPoint!

Unless Modifier

The unless modifier in Ruby is used when we want to modify an expression. It contains a statement on its left-side and a condition on its right.

Syntax

The syntax of the unless modifier is shown below.

statement unless condition

Example 3

Consider the code shown below

# unless modifier example

# variable num
num = 0

# statement - unless - condition
num += 5 unless num.zero?
   puts(num)

Output

0
raja
Updated on 25-Jan-2022 11:18:14

Advertisements