Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: unless vs if not

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?

like image 845
NullVoxPopuli Avatar asked Sep 22 '11 19:09

NullVoxPopuli


People also ask

Should I use unless in Ruby?

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.

What is the difference between if and unless statement in Ruby?

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.

Is unless opposite of if?

unless is the exact opposite of if . It's a negated if . In other words, the following three examples are equivalent.

Do not use unless With else?

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.


1 Answers

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.

like image 76
derp Avatar answered Sep 21 '22 11:09

derp