Introduction
Before starting this blog, let's understand what exactly is Unless, "I don't want you to give that number to anyone unless it's an emergency, you understand?" this is an unless statement with reference to English, and I know you understand the use of Unless with just a simple example like this and trust me Unless in Ruby is also this easy to understand. So let’s begin with our topic now.
Unless Statement
Ruby has a special statement known as the unless statement. When the provided condition is false, this statement is executed. It is the inverse of an if statement. The block of code in the if statement executes once the given condition is true, whereas the block of code in the unless statement executes once the given condition is false.
Unless a statement is used when we need to display a false condition, we cannot use if statement and or operator to print false statements because if statement and or operator always works on true conditions.
Syntax:
unless conditional [then]
code
[else code ]
End
If the conditional is false, the code is executed. If the conditional is true, the code in the otherwise clause is run.
Let's understand it with the help of an example
# variable n
n = 1
# using unless statement
unless n > 4
# condition is false
# this will print as
puts "Welcome to Coding ninjas!"
else
puts "Hello, Coding ninjas!"
End
Output:
Welcome to Coding ninjas!
Here is a flowchart for your better understanding,