Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't understand "unless" keyword in Ruby

Tags:

ruby

I'm not a native English speaker. I know it sounds stupid nonetheless. I write in Python & C. But I can't quite understand how unless works.

Is it healthy to think of it from a logical standpoint? Eg, consider the if keyword: if condition. If condition is true, the code runs. What's the logical explanation for unless?

Is there any other way to think of it?

like image 684
Sreejith Ramakrishnan Avatar asked Nov 06 '12 05:11

Sreejith Ramakrishnan


People also ask

What does unless mean in Ruby?

Ruby provides a special statement which is referred as unless statement. This statement is executed when the given condition is false. It is opposite of if statement.

What is the difference between if and unless statement in Ruby explain with an example?

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.


2 Answers

unless x is equivalent to if !x

like image 87
pje Avatar answered Sep 29 '22 12:09

pje


Ruby unless modifier:

Syntax: code unless conditional

Executes code if conditional is false.

Example:

$var =  1
print "1 -- Value is set\n" if $var
print "2 -- Value is set\n" unless $var

$var = false
print "3 -- Value is set\n" unless $var

This will produce following result:

1 -- Value is set

3 -- Value is set

like image 41
del Avatar answered Sep 29 '22 10:09

del