Can anyone explain me the difference between if
and unless
and when to use it?
We use the conjunction unless to mean 'except if'. The clause which follows unless is a subordinate clause (sc): it needs a main clause (mc) to make a complete sentence. When unless comes before the main clause, we use a comma: Unless [SC]it rains, [MC]we'll go for a picnic by the river tomorrow.
Unless is used to describe something that will happen if something else doesn't happen. For example, "I will walk to school unless it rains," which means that I will walk to school if it does not rain. "Not unless" is a little more situational.
unless
is just a negated if
. That is, it executes whatever it contains if the condition is not true.
unless foo? # blabla end
Simply means
if !foo? # blabla end
It's all a matter of what you find easier to read, really.
See also: Unless, The Abused Ruby Conditional
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