Ruby: unless vs if not

RubyCoding Style

Ruby Problem Overview


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 Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

I use unless every time, except when there is an else clause.

So, I'll use

unless blah_blah
  ...
end

but if there is an else condition, I'll use if not (or if !)

if !blah_blah
 ...
else
 ...
end

After using if ! for years and years and years, it actually took me a while to get used to unless. Nowadays I prefer it in every case where reading it out loud sounds natural.

I'm also a fan of using a trailing unless

increment_by_one unless max_value_reached I'm using these method/variable names obviously as a readability example - the code's structure should basically follow that pattern, in my opinion.

In a broader sense, the structure should be: take_action unless exception_applies

Solution 3 - Ruby

if not condition is rarely used. 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.

Also see making sense with Ruby unless for further suggestions about unless coding style.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullVoxPopuliView Question on Stackoverflow
Solution 1 - RubyderpView Answer on Stackoverflow
Solution 2 - RubyjeffluntView Answer on Stackoverflow
Solution 3 - RubySimone CarlettiView Answer on Stackoverflow