开发者

Difference - unless / if

Can anyone explain me the difference between if and unless开发者_如何学Go and when to use it?


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


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 simply equivalent to if not. When you use which is a personal preference.


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-block
  • unless 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.


As a ruby on rails dev its best to follow best practices maintain code readability. My answer is not directly related to this question but it might help someone, Try using if as much as possible instead of unless For example, instead of unless comments.empty? its better to use if comments.present?, instead of unless comments.present? try using if comments.blank?, blank? checks for both empty and nil.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜