Difference - unless / if

后端 未结 5 1095
无人共我
无人共我 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.

提交回复
热议问题