Ruby 语法
系统讲解 Ruby 源码文件规范、空白消歧、行尾续行、大小写敏感标识符、40 个保留字、Here Document 多行字符串、BEGIN/END 钩子及单双行注释。
学完这一章,你能够
- 系统讲解 Ruby 源码文件规范、空白消歧、行尾续行、大小写敏感标识符、40 个保留字、Here Document 多行字符串、BEGIN/END 钩子及单双行注释。
首个 .rb 脚本、空白消歧与语句续行
Ruby 源文件约定以 `.rb` 作为扩展名。将 `puts "Hello, Ruby!"` 写入 `test.rb`(Unix 下可在首行添加 `#!/usr/bin/ruby -w`),在终端执行 `ruby test.rb` 即可打印 `Hello, Ruby!`。下面依次展开构成 Ruby 词法与句法基础的核心规则。
字符串字面量之外的空格与制表符通常会被忽略,但在存在语法歧义时空白会直接改变解析结果:例如 `a + b` 会被解析为二元加法,而 `a +b`(`+` 紧贴 `b`)会被解析为以一元 `+b` 作为实参调用方法 `a(+b)`,开启 `-w` 时解释器会发出歧义警告。语句结束通常由换行符或分号标识;若行尾是 `+`、`-` 等运算符或反斜杠 `\`,解释器会自动将下一行视为同一条语句的延续。
标识符命名与 40 个保留字
Ruby 标识符用于命名变量、常量与方法,可由字母、数字和下划线 `_` 组成,且严格区分大小写(`Ram` 与 `RAM` 完全不同;首字母大写还决定其属于常量)。下表列出了 Ruby 的 40 个核心保留字,它们不能用作普通变量或常量名称,但在语法允许的上下文中可以作为方法名(实际工程仍建议避免重名以保证可读性)。
Here Document 多行字符串
Here Document(简称 Heredoc)用于便捷书写多行文本:在 `<<` 后紧跟终止标识符(`<<` 与标识符间不能留空格),后续所有行直至单独成行的终止符均成为字符串内容。未加引号或双引号 `<<"EOF"` 遵循双引号插值与转义规则;单引号 `<<'EOF'` 原样保留文本不做插值;反引号 ``<<`EOC` `` 会把多行内容交给系统 Shell 执行并返回输出;同一条语句中还可堆叠多个 Heredoc(如 `print <<"foo", <<"bar"`)。现代 Ruby 2.3+ 还提供波浪号形式 `<<~EOF`,可自动剥离每行公共前导缩进。
BEGIN / END 钩子与注释基础
`BEGIN { ... }` 声明的代码块会在程序主体执行之前按出现顺序(FIFO)运行,用于前置初始化;`END { ... }` 声明的代码块则在程序即将结束时按出现反序(LIFO)执行,用于清理收尾。因此即便在源码中先写 `puts "这是主 Ruby 程序"`、再写 `END` 和 `BEGIN`,实际运行输出顺序仍严格为“初始化 → 主程序 → 停止”。
Ruby 注释在运行时会被完全忽略:以 `#` 开头可注释整行,也可紧跟在表达式右侧充当行尾注释,连续多行 `#` 可构成段落说明;此外还能用顶格书写的 `=begin` 与 `=end` 包裹大段嵌入式块注释。
Ruby 核心保留字对照表(共 40 项)
| 第 1 列 | 第 2 列 | 第 3 列 | 第 4 列 |
| BEGIN | do | next | then |
| END | else | nil | true |
| alias | elsif | not | undef |
| and | end | or | unless |
| begin | ensure | redo | until |
| break | false | rescue | when |
| case | for | retry | while |
| class | if | return | yield |
| def | in | self | __FILE__ |
| defined? | module | super | __LINE__ |
离线校验空白消歧、40 个保留字、Here Document 变体与 BEGIN/END 钩子顺序
展开查看收起
"""Offline Ruby 3.x semantic verification lab for Chapter 09 (syntax)."""
import json
import re
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_whitespace_disambiguation_and_line_continuation():
# Ruby whitespace rule: `a + b` -> binary add; `a +b` -> method call `a(+b)`
def classify_expr(expr):
if re.match(r"^[a-z_]\w*\s+\+\s+[a-z_]\w*$", expr):
return "binary_add"
if re.match(r"^[a-z_]\w*\s+\+[a-z_]\w*$", expr):
return "method_call_with_unary_plus"
return "other"
continued = "total = 10 +\n 20 +\n 30"
joined_val = 10 + 20 + 30
expected = {
"a_space_plus_space_b": "binary_add",
"a_space_plusb": "method_call_with_unary_plus",
"line_continuation_sum": 60,
"has_trailing_operator": True,
}
actual = {
"a_space_plus_space_b": classify_expr("a + b"),
"a_space_plusb": classify_expr("a +b"),
"line_continuation_sum": joined_val,
"has_trailing_operator": continued.splitlines()[0].rstrip().endswith("+"),
}
return {
"name": "whitespace_disambiguation_and_line_continuation",
"summary": "验证 Ruby 空白消歧规则(a + b 与 a +b)以及行尾运算符自动续行语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_identifier_case_sensitivity_and_reserved_words():
reserved_40 = {
"BEGIN", "END", "alias", "and", "begin", "break", "case", "class", "def", "defined?",
"do", "else", "elsif", "end", "ensure", "false", "for", "if", "in", "module",
"next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super",
"then", "true", "undef", "unless", "until", "when", "while", "yield", "__FILE__", "__LINE__",
}
expected = {
"reserved_count": 40,
"case_distinct": True,
"class_is_reserved": True,
"ClassName_is_valid_const": True,
}
actual = {
"reserved_count": len(reserved_40),
"case_distinct": "Ram" != "RAM",
"class_is_reserved": "class" in reserved_40,
"ClassName_is_valid_const": "ClassName" not in reserved_40 and "ClassName"[0].isupper(),
}
return {
"name": "identifier_case_sensitivity_and_reserved_words",
"summary": "校验 Ruby 标识符大小写敏感规则及 40 个经典保留字集合完整性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_heredoc_variants_and_stacking():
# Bare <<EOF / <<"EOF" support interpolation, <<'EOF' disables interpolation, <<~EOF strips common indent
val = "Ruby"
double_doc = f" Hello {val}\n"
single_doc = " Hello #{val}\n"
squiggly_doc = "Hello Ruby\n"
stacked = [" I said foo.\n", " I said bar.\n"]
expected = {
"double_interpolated": " Hello Ruby\n",
"single_literal": " Hello #{val}\n",
"squiggly_dedented": "Hello Ruby\n",
"stacked_joined": " I said foo.\n I said bar.\n",
}
actual = {
"double_interpolated": double_doc,
"single_literal": single_doc,
"squiggly_dedented": squiggly_doc,
"stacked_joined": "".join(stacked),
}
return {
"name": "heredoc_variants_and_stacking",
"summary": "验证 Here Document 的默认/双引号/单引号/波浪号去缩进(<<~)与多段堆叠拼接语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_begin_end_hooks_and_comments():
events = []
begins = ["初始化 Ruby 程序"]
mains = ["这是主 Ruby 程序"]
ends = ["停止 Ruby 程序"]
for b in begins:
events.append(b)
for m in mains:
events.append(m)
for e in reversed(ends):
events.append(e)
sample_src = '# 行首注释\nname = "Madisetti" # 行尾注释\n=begin\n多行注释\n=end\n'
code_lines = []
in_block = False
for ln in sample_src.splitlines():
if ln.startswith("=begin"):
in_block = True
continue
if ln.startswith("=end"):
in_block = False
continue
if in_block or ln.lstrip().startswith("#"):
continue
code_lines.append(ln.split("#", 1)[0].strip())
expected = {
"hook_order": ["初始化 Ruby 程序", "这是主 Ruby 程序", "停止 Ruby 程序"],
"effective_code": ['name = "Madisetti"'],
}
actual = {"hook_order": events, "effective_code": code_lines}
return {
"name": "begin_end_hooks_and_comments",
"summary": "验证 BEGIN/主程序/END 执行次序以及 # 单行注释与 =begin/=end 块注释剥离行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_whitespace_disambiguation_and_line_continuation(),
case_identifier_case_sensitivity_and_reserved_words(),
case_heredoc_variants_and_stacking(),
case_begin_end_hooks_and_comments(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`<<EOF` 会保留每行原样前导空格,且结束标记 `EOF` 必须顶格;`<<~EOF`(Ruby 2.3+)会自动计算并剥离所有非空行的公共最小缩进,且允许结束标记随代码缩进对齐。