Difference - unless / if
The difference between if
and unless
is that they are exact opposites of each other:
if
takes a condition, a then-block and an optional else-block, and it evaluates the then-block if the condition is truthy, otherwise it evaluates the else-blockunless
takes a condition, a then-block and an optional else-block, and it evaluates the then-block if the condition is falsy, otherwise it evaluates the else-block
Or, in other words: they mean pretty much the same thing in Ruby as they do in English.
unless
is simply equivalent to if not
. When you use which is a personal preference.
Using 'unless' is straightforward to me when there is one argument, but I find it confusing when there are several. And when using ||
instead of &&
.
"Unless this or that" is just harder for my brain. "if not this and not that" is easier.
It's going to be harder to maintain this code in the future if I use it. So I don't.
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