Sreejith Ramakrishnan Sreejith Ramakrishnan - 5 months ago 12
Ruby Question

Can't understand "unless" keyword in 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?

del del
Answer

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