Ruby 简明教程
Ruby - if…else, case, unless
Ruby 提供条件结构,这是现代语言中非常普遍的。在此,我们将解释 Ruby 中提供的所有条件语句和修饰符。
Ruby offers conditional structures that are pretty common to modern languages. Here, we will explain all the conditional statements and modifiers available in Ruby.
Ruby if…else Statement
Syntax
if conditional [then]
code...
[elsif conditional [then]
code...]...
[else
code...]
end
if 表达式用于条件执行。值 false 和 nil 为 false,其他所有值为 true。请注意,Ruby 使用 elsif,而不是 else if 或 elif。
if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif.
在条件为真时执行代码。如果条件不为真,则执行 else 子句中指定代码。
Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed.
if 表达式的条件由保留字 then、换行符或分号与代码分隔。
An if expression’s conditional is separated from code by the reserved word then, a newline, or a semicolon.
Ruby unless Statement
Ruby case Statement
Syntax
case expression
[when expression [, expression ...] [then]
code ]...
[else
code ]
end
比较用例指定的表达式和使用 === 运算符指定的表达式,并执行与之匹配的 when 子句的代码。
Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches.
用例指定的表达式作为左操作数进行评估。如果没有与之匹配的 when 子句,case 将执行 else 子句的代码。
The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause.
when 语句的表达式由保留字 then、换行符或分号与代码分隔。因此:
A when statement’s expression is separated from code by the reserved word then, a newline, or a semicolon. Thus −
case expr0
when expr1, expr2
stmt1
when expr3, expr4
stmt2
else
stmt3
end
基本上类似于以下内容:
is basically similar to the following −
_tmp = expr0
if expr1 === _tmp || expr2 === _tmp
stmt1
elsif expr3 === _tmp || expr4 === _tmp
stmt2
else
stmt3
end