Difference - unless / if

后端 未结 5 1096
无人共我
无人共我 2020-12-04 20:02

Can anyone explain me the difference between if and unless and when to use it?

相关标签:
5条回答
  • 2020-12-04 20:13

    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.

    0 讨论(0)
  • 2020-12-04 20:21

    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.

    0 讨论(0)
  • 2020-12-04 20:21

    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 讨论(0)
  • 2020-12-04 20:26

    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

    0 讨论(0)
  • 2020-12-04 20:28

    unless is simply equivalent to if not. When you use which is a personal preference.

    0 讨论(0)
提交回复
热议问题