开发者

Ruby: unless vs if not

I开发者_C百科 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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜