gpt4 book ai didi

ruby - 如果没有要检查的表达式,Ruby case 表达式意味着什么?

转载 作者:太空宇宙 更新时间:2023-11-03 17:45:08 25 4
gpt4 key购买 nike

以 Ruby 表达式为例:

case
when 3 then "foo"
when 4 then "bar"
end

得知这不是语法错误,我感到很惊讶。相反,它的计算结果为 "foo"!

为什么?这里应用的语法和评估规则是什么?

最佳答案

在这种形式的 case 表达式中,then 子句与词法上第一个 when 子句相关联,该子句的计算结果为 truthy 评估值(value)。

参见 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:
    1. […]
    2. 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:
    1. 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.
    2. 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.
    3. 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.
    4. 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 more when clauses. The first when 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 successful when clause, or nil if there is no such clause.

关于ruby - 如果没有要检查的表达式,Ruby case 表达式意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40133098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com