Understanding "If" vs "unless" in ruby

In my quest to learn the Ruby programming language as a Javascript engineer the unless
conditional keyword was a new one for me.
At the end of this post, it is expected that the user should be able to understand the unless
conditional Ruby keyword and how it is different from the if
keyword
While reading various posts and books about Ruby programming language, you might come across a phrase that says "unless
keyword in Ruby is the opposite of the if
keyword". Although this statement is helpful, it can also be confusing when you're reading actual code. That said, I came across an illustration that made me understand this concept so much better.
if 2 > 3
print "this is great"
else
print "what is this"
end
The above is easy to understand, the condition is false, so the program skips the first statement and prints the else statement.
unless 2>3
print "this is great"
else
print "what is this"
end
As I mentioned previously, the conditions share similar syntax, but their difference lies in the first condition's evaluation.
in the case of the if
conditional, if the first condition is true then the first statement is executed. while the unless
conditional only executes the first statement if the condition evaluates to false
using the example above 2 > 3
we know that this condition is false because 2 is less than 3. If this same 2 > 3
condition is in the if
block and since it is false, the else
statement is executed. The opposite is the case for the unless
block where the first statement is always executed as long as the first evaluation is false
Subscribe to my newsletter
Read articles from Justice Otuya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Justice Otuya
Justice Otuya
I'm Justice Otuya, a seasoned Frontend Engineer with over six years of experience in software engineering. I specialize in building customer-facing web applications and solving complex business problems with innovative solutions.