Ruby 条件判断
系统剖析 Ruby 真值规则(仅 false 与 nil 为假)、if/elsif/else 语句、unless 反向分支、后置 if/unless 修饰符以及基于 === 的 case/when 多路匹配。
学完这一章,你能够
- 系统剖析 Ruby 真值规则(仅 false 与 nil 为假)、if/elsif/else 语句、unless 反向分支、后置 if/unless 修饰符以及基于 === 的 case/when 多路匹配。
Ruby 真值规则与 if / elsif / else
在 Ruby 条件判断中有一条必须牢记的核心规则:**只有 `false` 和 `nil` 被判定为假(falsy),包括整数 `0`、空字符串 `""` 与空数组 `[]` 在内的所有其他对象皆为真(truthy)**。多路分支使用 `if ... elsif ... else ... end`(关键字写作 `elsif`,切勿写成 `else if` 或 `elif`)。多行书写时通常省略 `then`;若压缩为单行(如 `if a == 4 then a = 7 end`),则必须使用 `then`(或分号)分隔条件与执行体。
后置 if 修饰符与 unless 语句 / 修饰符
对于仅包含单条语句的条件动作,Ruby 提供简洁的后置 `if` 修饰符 `code if condition`:先检查右侧条件,为真时才执行左侧表达式(例如 `$debug = 1; print "debug\n" if $debug` 会输出 `debug`)。
`unless` 与 `if` 语义恰好相反:条件为假时执行主体,为真时执行可选的 `else` 分支(注意 `unless` 不允许接 `elsif`,且与 `else` 混用容易绕晕阅读者,通常建议仅在不带 `else` 的否定守卫场景使用)。后置形式 `code unless conditional` 同样在右侧条件为假时执行左侧语句——示例中 `$var = 1` 时 `if $var` 输出第 1 行而 `unless $var` 不输出第 2 行,将 `$var` 置为 `false` 后 `unless $var` 才输出第 3 行。
case / when 语句与 === 匹配机制
`case expression` 会依次使用 `when` 子句里的匹配对象作为接收者调用 `===` 运算符去比较目标值(即 `when_expr === target`),命中首个返回真值的 `when` 后执行其分支并自动结束(无需 `break` 防止穿透)。单个 `when` 支持逗号列举多个候选模式,单行写法同样需加 `then`。利用 `Range#===`,`$age = 5` 可优雅地落入 `when 3..6` 并输出 `小孩`。
当省略 `case` 后面的目标表达式时,Ruby 会按顺序评估每个 `when` 后的布尔条件并执行第一个为真的分支,适合作为整洁的多条件替代写法(如 `bar = true` 时命中 `when bar` 输出 `bar is true`)。
离线校验 Ruby 真值规则、if/unless 修饰符及 case === 匹配与无表达式分支
展开查看收起
"""Offline Ruby 3.x semantic verification lab for Chapter 16 (decision)."""
import json
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def ruby_truthy(val) -> bool:
return not (val is False or val is None)
def case_ruby_truthiness_and_if_elsif_else():
# In Ruby ONLY false and nil are falsy; 0, "", [] are ALL truthy!
table = {
"false": ruby_truthy(False),
"nil": ruby_truthy(None),
"0": ruby_truthy(0),
"empty_str": ruby_truthy(""),
"empty_arr": ruby_truthy([]),
}
x = 1
if x > 2:
branch = "x 大于 2"
elif x <= 2 and x != 0:
branch = "x 是 1"
else:
branch = "无法得知 x 的值"
a = 4
if a == 4:
a = 7
expected = {
"truthiness": {"false": False, "nil": False, "0": True, "empty_str": True, "empty_arr": True},
"if_elsif_output": "x 是 1",
"one_line_then_result": 7,
}
actual = {"truthiness": table, "if_elsif_output": branch, "one_line_then_result": a}
return {
"name": "ruby_truthiness_and_if_elsif_else",
"summary": "验证 Ruby 仅 false 与 nil 为假(0、空串、空数组皆为真)及 if/elsif/else 与单行 then 规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_if_and_unless_statement_modifiers():
out = []
debug = 1
if ruby_truthy(debug):
out.append("debug")
var = 1
if ruby_truthy(var):
out.append("1 -- 这一行输出")
if not ruby_truthy(var):
out.append("2 -- 这一行不输出")
var = False
if not ruby_truthy(var):
out.append("3 -- 这一行输出")
expected = ["debug", "1 -- 这一行输出", "3 -- 这一行输出"]
return {
"name": "if_and_unless_statement_modifiers",
"summary": "验证后置 if 与 unless 语句修饰符在不同真值状态下的执行结果",
"expected": expected,
"actual": out,
"passed": out == expected,
}
def case_unless_branch_negation_semantics():
def eval_unless(x):
if not (x > 2):
return "x 小于或等于 2"
else:
return "x 大于 2"
expected = {"x_1": "x 小于或等于 2", "x_5": "x 大于 2", "supports_elsif": False}
actual = {"x_1": eval_unless(1), "x_5": eval_unless(5), "supports_elsif": False}
return {
"name": "unless_branch_negation_semantics",
"summary": "校验 unless/else 反向分支求值语义并确认 Ruby unless 不支持 elsif 子句",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_case_when_triple_equals_and_condition_form():
def classify_age(age):
for lo, hi, label in [(0, 2, "婴儿"), (3, 6, "小孩"), (7, 12, "child"), (13, 18, "少年")]:
if lo <= age <= hi:
return label
return "其他年龄段的"
# Condition-less `case` evaluates first truthy `when`
foo, bar, quu = False, True, False
cond_out = None
for cond, msg in [(foo, "foo is true"), (bar, "bar is true"), (quu, "quu is true")]:
if ruby_truthy(cond):
cond_out = msg
break
expected = {
"age_5": "小孩",
"age_25": "其他年龄段的",
"conditionless_case": "bar is true",
"uses_case_eq_operator": "===",
}
actual = {
"age_5": classify_age(5),
"age_25": classify_age(25),
"conditionless_case": cond_out,
"uses_case_eq_operator": "===",
}
return {
"name": "case_when_triple_equals_and_condition_form",
"summary": "验证 case/when 使用 === 运算符匹配范围与无表达式 case 首个真值分支语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_ruby_truthiness_and_if_elsif_else(),
case_if_and_unless_statement_modifiers(),
case_unless_branch_negation_semantics(),
case_case_when_triple_equals_and_condition_form(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
会输出 `yes`。因为 Ruby 中只有 `false` 和 `nil` 为假,整数 `0` 属于 `Integer` 对象,在条件判断中为真。