以 Ruby 表达式为例:
case
when 3 then "foo"
when 4 then "bar"
end
我很惊讶地发现这不是语法错误。相反,它的计算结果为 "foo"
!
最佳答案
在这种形式的 case
表达式中,then
子句与词法上第一个 when
子句关联,其计算结果为 truthy 评估值。
参见ISO Ruby Language Specification的§11.5.2.2.4语义条款b) 2) (粗体强调我的):
Semantics
A case-expression is evaluated as follows:
- a) […]
- b. The meaning of the phrase “O is matching” in Step c) is defined as follows:
- […]
- If the case-expression is a case-expression-without-expression, O is matching if and only if O is a trueish object.
- c) Take the following steps:
- Search the when-clauses in the order they appear in the program text for a matching when-clause as follows:
- i) If the operator-expression-list of the when-argument is present:
- I) For each of its operator-expressions, evaluate it and test if the resulting value is matching.
- II) If a matching value is found, other operator-expressions, if any, are not evaluated.
- ii) If no matching value is found, and the splatting-argument (see 11.3.2) is present:
- I) Construct a list of values from it as described in 11.3.2. For each element of the resulting list, in the same order in the list, test if it is matching.
- II) If a matching value is found, other values, if any, are not evaluated.
- iii) A when-clause is considered to be matching if and only if a matching value is found in its when-argument. Later when-clauses, if any, are not tested in this case.
- If one of the when-clauses is matching, evaluate the compound-statement of the then-clause of this when-clause. The value of the case-expression is the resulting value.
- If none of the when-clauses is matching, and if there is an else-clause, then evaluate the compound-statement of the else-clause. The value of the case-expression is the resulting value.
- Otherwise, the value of the case-expression is
nil
.
RDoc documentation虽然不太精确,但也指出当省略条件时,真实性是选择标准;词法顺序决定了 when
子句的检查顺序(粗体强调我的):
case
The case statement operator. Case statements consist of an optional condition, which is in the position of an argument to
case
, and zero or morewhen
clauses. The firstwhen
clause to match the condition (or to evaluate to Boolean truth, if the condition is null) "wins", and its code stanza is executed. The value of the case statement is the value of the successfulwhen
clause, ornil
if there is no such clause.
关于ruby - 如果没有要检查的表达式,Ruby case 表达式意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40133098/