I find myself preferring if not
rather than unless
. Is there a proper way to write that sort of condition? How do people generally feel about unless
?
Ruby programmers (usually coming from other languages) tend to prefer the use if ! condition . On the other side, unless is widely use in case there is a single condition and if it sounds readable.
In if statement, the block executes once the given condition is true, however in unless statement, the block of code executes once the given condition is false.
unless is the exact opposite of if . It's a negated if . In other words, the following three examples are equivalent.
There is nothing stopping anyone from using unless - else . It is perfectly valid. But the else part of unless-else is a double negative. In some cases, unless is easy to comprehend.
I hope this helps you: https://github.com/rubocop-hq/ruby-style-guide#if-vs-unless
Prefer unless over if for negative conditions (or control flow ||).
# bad do_something if !some_condition # bad do_something if not some_condition # good do_something unless some_condition
I personally agree with what's written there choosing unless something
over if !something
for modifiers and simple ones and when there's an else
prefer if
.
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