Ruby unless Statement Tutorial

  • Post author:
  • Post category:Ruby

In this section, we will learn what the unless statement is and how to use it in Ruby.

Note: we’re assuming you’re familiar with the Ruby if statement as well.

What is unless Statement in Ruby?

The Ruby unless statement works like the if statement with the exception that:

While an if statement’s block will only run if the result of its condition is true, the unless statement works only if the result of the condition is false!

Ruby unless Statement Syntax:

unless condition

#instructions to be run if the result of the condition is false…

end

`unless`: in order to create an unless statement, we start with the keyword `unless`.

`condition`: this is the expression that we want to evaluate and only if the result of this condition is false, in that case the body of the unless statement will run.

`end`: we close the body of an unless statement using the `end` clause. Basically, this is the closing border of the body of an unless statement.

Now within the body of the unless statement, we can put any instructions we want to be executed if the condition of the `unless` statement resulted false.

Note: the `unless` statement also takes an optional `else` statement as well.

Here’s the syntax of using an `else` statement:

unless condition

#instructions to be run if the result of the condition is false

else

#instructions to be run if the result of the condition was true.

end

Note that the body of the else statement will only run if the result of the `unless` condition was true!

Example: using unless statement in Ruby

first_name = "John"

unless first_name == "Omid"

puts "The value of the first_name variable is not Omid"

end

Output:

The value of the first_name variable is not Omid

How does unless statement work in Ruby?

In the last example, the condition of the `unless` statement is to see of the `first_name` variable’s value is equal to the value `Omid`. Now because the value of the `first_name` variable is not equal to the value `Omid` then the result of the comparison is false and so the body of the `unless` statement will RUN as a result.

Difference between if statement and unless statement in Ruby

The main difference between the if statement and the unless statement is based on what condition the body of these statements runs.

For the if statement, the body will only run if the result of the condition is true.

But for the unless statement, the body will only run if the result of the condition is false.

Leave a Reply