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?
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.
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.
unless x
is equivalent to if !x
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With