蓝色天空网mbsky.com · 知识 · 实践 · 创造Ruby · 本地阅读预览
教程 / 编程语言 / Ruby

Ruby 中文编码

说明 Ruby 源码文件包含中文时的编码报错机理、UTF-8 魔术注释规范、Ruby 2.0+/3.x 默认编码变化以及文件保存编码一致性要求。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

中文源码编码报错机理与历史背景

当脚本中仅含英文字符时通常不会暴露编码问题,但在包含中文字符串(如 `puts "你好,世界!"`)时,若解释器按 `US-ASCII` 读取源码就会抛出 `invalid multibyte char (US-ASCII)` 语法错误。该现象主要出现在默认源码编码为 `US-ASCII` 的 Ruby 1.9 时代;通过在文件首部加入魔术注释 `# -*- coding: UTF-8 -*-`(Emacs 风格)或 `# coding=utf-8` 即可显式告知解释器按 UTF-8 解析。需补充的是,自 Ruby 2.0 起(含 Ruby 3.x)默认源码编码已改为 UTF-8,但显式声明编码注释仍有助于兼容旧环境与明确文件约定。

UTF-8 魔术注释实例与编辑器保存规范

若脚本首行带有 Unix shebang(`#!/usr/bin/ruby -w`),编码魔术注释必须紧随其后置于第二行(无 shebang 时置于第一行),随后运行 `puts "你好,世界!"` 即可正确输出中文内容,无乱码或语法报错。

在日常编写含中文的 Ruby 源码时,需同时落实两点:其一,在文件顶部正确声明编码魔术注释(现代项目常与 `# frozen_string_literal: true` 配合使用);其二,务必将编辑器保存文件的实际字符集设为无 BOM 的 UTF-8,避免出现声明为 UTF-8 而磁盘字节实为 GBK 的解码冲突。

离线校验 US-ASCII 多字节报错复现、魔术注释解析与文件编码一致性

python · 阅读源码
"""Offline Ruby 3.x semantic verification lab for Chapter 06 (encoding)."""
import json
import re

VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"

MAGIC_RE = re.compile(r"coding\s*[:=]\s*([A-Za-z0-9_-]+)", re.IGNORECASE)


def detect_ruby_source_encoding(raw_bytes: bytes, ruby_major: int = 3) -> str:
    lines = raw_bytes.splitlines()[:2]
    check_lines = lines[:2] if (lines and lines[0].startswith(b"#!")) else lines[:1]
    for ln in check_lines:
        if ln.lstrip().startswith(b"#"):
            m = MAGIC_RE.search(ln.decode("ascii", errors="ignore"))
            if m:
                return m.group(1).upper()
    return "UTF-8" if ruby_major >= 2 else "US-ASCII"


def case_us_ascii_multibyte_syntax_error_legacy():
    src = '#!/usr/bin/ruby -w\n\nputs "你好,世界!";\n'.encode("utf-8")
    enc_19 = detect_ruby_source_encoding(src, ruby_major=1)
    try:
        src.decode("ascii")
        err = None
    except UnicodeDecodeError:
        err = "invalid multibyte char (US-ASCII)"
    expected = {"ruby19_default": "US-ASCII", "error": "invalid multibyte char (US-ASCII)"}
    actual = {"ruby19_default": enc_19, "error": err}
    return {
        "name": "us_ascii_multibyte_syntax_error_legacy",
        "summary": "复现 Ruby 1.9 默认 US-ASCII 源码编码下读取 UTF-8 中文字符触发 invalid multibyte char 报错的机理",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_magic_encoding_comment_parser():
    samples = [
        b"#!/usr/bin/ruby -w\n# -*- coding: UTF-8 -*-\nputs 'hi'\n",
        b"# coding=utf-8\nputs 'hi'\n",
        b"# encoding: UTF-8\nputs 'hi'\n",
    ]
    detected = [detect_ruby_source_encoding(s, ruby_major=1) for s in samples]
    expected = {"detected": ["UTF-8", "UTF-8", "UTF-8"]}
    actual = {"detected": detected}
    return {
        "name": "magic_encoding_comment_parser",
        "summary": "解析 Emacs 风格与简写编码魔术注释(允许紧跟 shebang 位于第 2 行)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_utf8_default_and_frozen_string_literal():
    src = '#!/usr/bin/ruby -w\n# frozen_string_literal: true\nputs "你好,世界!"\n'.encode("utf-8")
    enc_3 = detect_ruby_source_encoding(src, ruby_major=3)
    frozen = b"frozen_string_literal: true" in src
    expected = {"ruby3_default": "UTF-8", "frozen_enabled": True, "decoded_text": "你好,世界!"}
    actual = {
        "ruby3_default": enc_3,
        "frozen_enabled": frozen,
        "decoded_text": src.decode("utf-8").split('"')[1],
    }
    return {
        "name": "utf8_default_and_frozen_string_literal",
        "summary": "验证 Ruby 2.0+/3.x 默认 UTF-8 源码编码及 frozen_string_literal 魔术注释共存",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_file_encoding_consistency_check():
    text = "你好,世界!"
    utf8_bytes = text.encode("utf-8")
    gbk_bytes = text.encode("gbk")
    utf8_ok = utf8_bytes.decode("utf-8") == text
    try:
        gbk_bytes.decode("utf-8")
        mismatch_error = False
    except UnicodeDecodeError:
        mismatch_error = True
    expected = {"utf8_roundtrip_ok": True, "gbk_under_utf8_fails": True, "utf8_byte_len": 18}
    actual = {"utf8_roundtrip_ok": utf8_ok, "gbk_under_utf8_fails": mismatch_error, "utf8_byte_len": len(utf8_bytes)}
    return {
        "name": "file_encoding_consistency_check",
        "summary": "校验文件声明编码与编辑器实际保存编码一致的重要性(GBK 字节按 UTF-8 解析将解码失败)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_us_ascii_multibyte_syntax_error_legacy(),
        case_magic_encoding_comment_parser(),
        case_utf8_default_and_frozen_string_literal(),
        case_file_encoding_consistency_check(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器复现 Ruby 1.9 US-ASCII 解码报错、验证 Emacs 与简写魔术注释、核对 Ruby 3.x 默认 UTF-8 及 GBK/UTF-8 失配检测。
离线校验 US-ASCII 多字节报错复现、魔术注释解析与文件编码一致性

所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。

当前源码 SHA256:69ea377dae1a2527c512d2909839fc26ad865bda3efd84342071a3a475bb7532

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Ruby 中文编码实验

所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装原生 MRI Ruby 解释器)。

ZIP SHA256:a62d815e9bd1994aff4afa97c5614bed83883dfeedef1490cedca2cf5c5cca1d

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

如果源码第 1 行是 `#!/usr/bin/ruby -w`,编码魔术注释写在文件的第 3 行是否还能生效?

展开参考解答

不会生效。Ruby 规范要求编码魔术注释必须位于第 1 行;仅当第 1 行是 `#!` shebang 时,才允许顺延至第 2 行。

规范与官方依据