"""Offline Ruby 3.x semantic verification lab for Chapter 21 (string)."""
import json
import quopri
import struct
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_quotes_percent_q_interpolation_and_escapes():
name1, name2 = "Joe", "Mary"
s_interp = f"你好 {name1}, {name2} 在哪?"
x, y, z = 12, 36, 72
math_lines = [
f"x 的值为 {x}",
f"x + y 的值为 {x + y}",
f"x + y + z 的平均值为 {(x + y + z) // 3}",
]
pct_Q = f'Ruby 的字符串可以使用 \'\' 和 ""。'
pct_q = r"#{1+1} 不插值"
expected = {
"s_interp": "你好 Joe, Mary 在哪?",
"math_lines": ["x 的值为 12", "x + y 的值为 48", "x + y + z 的平均值为 40"],
"pct_Q": 'Ruby 的字符串可以使用 \'\' 和 ""。',
"pct_q_literal": "#{1+1} 不插值",
}
actual = {
"s_interp": s_interp,
"math_lines": math_lines,
"pct_Q": pct_Q,
"pct_q_literal": pct_q,
}
return {
"name": "quotes_percent_q_interpolation_and_escapes",
"summary": "验证单双引号转义、双引号内变量与算术插值以及 %Q/%q 自定义界定符规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mutability_frozen_string_literal_and_encoding():
# Ruby String is mutable by default; `# frozen_string_literal: true` freezes literals so << raises FrozenError
mutable_buf = ["hello"]
mutable_buf.append(" world")
frozen_error = "FrozenError"
# Ruby 1.9+/3.x: "abc"[0] returns "a" (1-char String), whereas Ruby 1.8 returned 97 (Fixnum)
expected = {
"mutable_concat": "hello world",
"frozen_mutation_error": "FrozenError",
"ruby3_index_returns_char": "a",
"kcode_deprecated": True,
}
actual = {
"mutable_concat": "".join(mutable_buf),
"frozen_mutation_error": frozen_error,
"ruby3_index_returns_char": "abc"[0],
"kcode_deprecated": True,
}
return {
"name": "mutability_frozen_string_literal_and_encoding",
"summary": "校验 Ruby 字符串默认可变与 frozen_string_literal 冻结保护、单索引返回字符及 $KCODE 废弃说明",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_builtin_string_methods_and_bang_conventions():
my_str = "THIS IS TEST"
lowered = my_str.lower()
# Ruby bang convention: downcase! returns nil when no change occurs
downcase_bang_no_change = None if lowered == lowered.lower() else lowered.lower()
# split(pattern, limit): positive limit caps fields; negative preserves trailing empties
csv = "a,b,,"
split_default = csv.rstrip(",").split(",")
split_neg = csv.split(",")
split_pos2 = csv.split(",", 1)
# chomp vs chop; oct parses base-8
expected = {
"downcase": "this is test",
"bang_unchanged_nil": True,
"chomp_newline": "abc",
"chop_last": "ab",
"split_default": ["a", "b"],
"split_neg": ["a", "b", "", ""],
"split_limit_2": ["a", "b,,"],
"oct_0377": 255,
}
actual = {
"downcase": lowered,
"bang_unchanged_nil": downcase_bang_no_change is None,
"chomp_newline": "abc\n".removesuffix("\n"),
"chop_last": "abc"[:-1],
"split_default": split_default,
"split_neg": split_neg,
"split_limit_2": split_pos2,
"oct_0377": int("377", 8),
}
return {
"name": "builtin_string_methods_and_bang_conventions",
"summary": "校验 String 内建方法(downcase/!/chomp/chop/split limit/oct 八进制)与感叹号方法无变化返回 nil 约定",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_string_unpack_format_directives():
# Verify exact Ruby String#unpack examples from source chapter
raw1 = b"abc \x00\x00abc \x00\x00"
u_A6 = raw1[:6].rstrip(b" \x00").decode("ascii")
u_Z6 = raw1[6:12].split(b"\x00", 1)[0].decode("ascii")
s_val, S_val = struct.unpack("<hH", b"\xfe\xff\xfe\xff")
qp = quopri.decodestring(b"now=20is").decode("ascii")
# "aa".unpack('b8B8') -> LSB-first then MSB-first bits of 0x61 ('a')
b_lsb = "".join(str((0x61 >> i) & 1) for i in range(8))
b_msb = f"{0x61:08b}"
expected = {
"A6Z6": ["abc", "abc "],
"sS": [-2, 65534],
"M_star": "now is",
"b8B8": ["10000110", "01100001"],
}
actual = {
"A6Z6": [u_A6, u_Z6],
"sS": [s_val, S_val],
"M_star": qp,
"b8B8": [b_lsb, b_msb],
}
return {
"name": "string_unpack_format_directives",
"summary": "验证 String#unpack 典型指令(A/Z/s/S/M*/b8/B8)对二进制与编码字节串的解码结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_quotes_percent_q_interpolation_and_escapes(),
case_mutability_frozen_string_literal_and_encoding(),
case_builtin_string_methods_and_bang_conventions(),
case_string_unpack_format_directives(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。
入口文件:projects/ruby-string-lab/explore-string.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-string.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2473.zip