Signup/Sign In

Ruby unless Condition

Before we start with unless, let's see some basic things which we have already seen before. We are doing this because, it explains your question Why Unless? So, we see about or operator, if keyword and unless keyword. OR operator returns true, even if one of the condition is true.

if condition with logical or operator in Ruby

In the above code a variable weight is assigned with a value 32. Then a condition is checked using OR operator.

If the weight is less than 35 or if the weight is greater than 70 it displays "You need to see a doctor".

Now, the first condition is checked weight < 35, this condition becomes true because the value of weight is 32 and OR operator doesn't check the second condition if the first condition is true. It simply returns true.

When the condition is true, it displays the message "You need to see a doctor". Now, consider the value of weight as 87.

if condition with logical or operator in Ruby

The first condition is checked weight < 35, the condition fails and it checks the second condition weight > 70, the condition is true, so the message is displayed. Now, what if the weight contains value between 35 and 70?

if condition with logical or operator in Ruby

As usual, the first condition is checked, it fails and the second condition is checked and it also fails. Therefore, the puts statement is not executed.

When we talk about if keyword, it is used to make a decision, whether to execute the set of code or not. But, what if wanted to test the opposite of if? That is, you want to execute the code only when the condition is false. This is where unless comes into picture.

Unless Example in Ruby

This program displays the message "You're eligible to Vote" when the age is greater than 18. The value stored in the variable age is 23.

When the condition is checked, it returns false and the puts statement is executed. This might be confusing.

Remember that unless is opposite of if.

You, can read this code statement as You're eligible to vote if your age is not less than 18. That is, it is similar to puts "You're eligible to Vote" if age > 18

If you're confused in reading the unless statement, simply read it in the opposite way of if statement.