Ruby Conditional
Ruby provides several common conditional structures. Here, we will explain all the conditional statements and modifiers available in Ruby.
Ruby if...elseStatement
Syntax
ifAn expression is used for conditional execution. The valuefalseandnilfalse is false, all other values are true. Note that Ruby uses elsif, not else if or elif.
Ifconditionalis true, then executecode. Ifconditionalis not true, then execute the one specified in the else clausecode。
Usually we omit the reserved word then. If you want to write a complete if expression on one line, you must separate the condition from the program block with then. As shown below:
Example
Try it »
The above example outputs:
x 是 1
Ruby ifModifier
Syntax
The if modifier phrase means that the expression on the left of if is executed only when the condition on the right of if is true. That is, ifconditionalis true, then executecode。
The above example outputs:
debug
Ruby unlessStatement
Syntax
The unless expression works opposite to the if expression, that is, ifconditionalis false, then executecode. Ifconditionalis true, then execute the one specified in the else clausecode。
Example
Try it »
The above example outputs:
x 小于或等于 2
Ruby unlessModifier
Syntax
Ifconditionalis false, then executecode。
Example
Try it »
The above example outputs:
1 -- 这一行输出 3 -- 这一行输出
Ruby caseStatement
Syntax
case first performs aexpressionmatching judgment, and then selects a branch based on the match result.
It uses the===operator to comparewhenthe specifiedexpression, and if they match, then executewhenthe content of that part.
Usually we omit the reserved word then. If you want to write a complete when expression on one line, you must separate the condition from the program block with then. As shown below:
Therefore:
Basically similar to:
Example
Try it »
The above example outputs:
child
When the "expression" part of case is omitted, the first when condition part that is true is evaluated.