Ruby Just
Ruby provides several very common conditional structures. Here we will explain all the conditional statements and the modifiers available in Ruby.
Ruby if...else statement
Syntax
if expressions are used for conditional execution. The values false and nil are false and all other values are true. Note that Ruby uses elsif instead of else if and elif.
If conditional is true, execute code. If conditional is not true, the code specified in the else clause is executed.
Usually we omit the reserved word then . If you want to write a complete if expression on a line, you must separate the conditional and program blocks with then. As shown below:
Instance
The output of the above example:
x is 1
Ruby if modifier
Syntax
if modifier indicates that the expression to the left of if is executed when the condition to the right of if is true. That is, if conditional is true, execute code.
Instance
The output of the above example:
Debug
Ruby unless Statement
grammar
unless and if have the opposite effect, ie if conditional is false, then code is executed. If conditional is true, the code specified in the else clause is executed.
Instance
The output of the above example is:
x is less than 2
Ruby unless modifier
Syntax
in case conditional False, then execute code。
Instance
The output of the above example:
1 -- this line of output 3 -- this line of output
Ruby case Statement
Syntax
case first matches a expression and then performs branch selection based on the matching result.
It uses the === operator to compare expression specified by when, and if it is consistent, execute when Part of the content.
Usually we omit the reserved word then . If you want to write the complete when expression on a line, you must separate the conditional and program blocks with then. As shown below:
So:
Basically similar to:
The output of the above example is:
Child
When the "expression" part of the case is omitted, the expression that the first when condition part is true is evaluated.