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

Ruby 环境

总览本地 Ruby 开发环境设置的四大主题、常见跨平台与 Windows 编辑器选型,以及交互式 Ruby(IRb)会话的基本用法。

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

学完这一章,你能够

本地环境设置路线

在正式编写业务代码前,建议先理清本地 Ruby 环境的配置脉络,依次掌握不同操作系统的安装方式以及解释器的启动控制机制。

环境配置主要涵盖四个关联主题:在 Linux/Unix 系统上编译或通过版本管理器安装 Ruby;在 Windows 上借助安装程序并配置系统路径;使用命令行选项控制解释器调试、语法检查与单行脚本执行;以及通过环境变量调整库搜索路径与默认选项。

常用编辑器与 IDE 选型

编写 Ruby 源码只需支持纯文本与 UTF-8 的编辑器。Windows 开发者常用 VS Code、EditPlus 等轻量编辑器,也可选用历史工具 RubyWin 或 RDE(Ruby Development Environment);在 Unix/Linux 以及 Windows 终端环境下,Vim/vi 凭借高效的键盘操作同样备受欢迎。现代大型项目也常配合 RubyMine 或 VS Code 的 Ruby LSP 插件获得补全与调试支持。

交互式 Ruby(IRb)体验与后续衔接

交互式 Ruby(IRb)随 Ruby 安装包默认附带,无需额外配置,在终端输入 `irb` 即可启动 REPL 会话并逐行查看求值结果。在示例会话中定义 `def hello ... end` 后输入 `hello` 即可立即看到 `Hello World` 输出;注意早期 Ruby 1.8 中 `def` 表达式返回 `nil`,而自 Ruby 2.1 起(含 Ruby 3.x)定义方法会返回方法名符号 `:hello`。语法细节将在后续章节展开。

完成环境认知并熟悉 `irb` 启动方式后,接下来将分别深入 Linux 与 Windows 平台的具体安装步骤以及第一个完整脚本的编写。

离线校验环境四大主题、编辑器清单、IRb 会话嵌套深度与返回值演进

python · 阅读源码
"""Offline Ruby 3.x semantic verification lab for Chapter 03 (environment)."""
import json
import shutil

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


def case_local_setup_topics_and_editors():
    topics = [
        "Linux/Unix Ruby 安装",
        "Windows Ruby 安装",
        "Ruby 命令行选项",
        "Ruby 环境变量",
    ]
    editors = {
        "cross_platform": ["VS Code", "Vim", "RubyMine"],
        "windows_legacy_and_tools": ["EditPlus", "RubyWin", "RDE"],
    }
    expected = {"topic_count": 4, "has_vscode": True, "has_vim": True, "legacy_ide_count": 3}
    actual = {
        "topic_count": len(topics),
        "has_vscode": "VS Code" in editors["cross_platform"],
        "has_vim": "Vim" in editors["cross_platform"],
        "legacy_ide_count": len(editors["windows_legacy_and_tools"]),
    }
    return {
        "name": "local_setup_topics_and_editors",
        "summary": "核对本地环境配置四大子主题以及跨平台与 Windows 编辑器/IDE 选型",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_irb_interactive_def_and_call():
    # Ruby 1.8 returned nil for `def hello`; Ruby 2.1+ returns `:hello` Symbol.
    def_return_ruby18 = "nil"
    def_return_ruby3 = ":hello"
    call_stdout = "Hello World\n"
    call_return = "nil"
    expected = {
        "def_return_ruby18": "nil",
        "def_return_ruby3": ":hello",
        "call_stdout": "Hello World\n",
        "call_return": "nil",
    }
    actual = {
        "def_return_ruby18": def_return_ruby18,
        "def_return_ruby3": def_return_ruby3,
        "call_stdout": call_stdout,
        "call_return": call_return,
    }
    return {
        "name": "irb_interactive_def_and_call",
        "summary": "模拟 IRb 中定义并调用 hello 方法,同时核对 Ruby 1.8(nil)与 Ruby 2.1+/3.x(:hello)的 def 返回值演进",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_irb_prompt_indent_depth_tracking():
    lines = [
        ("def hello", 0, 1),
        ('out = "Hello World"', 1, 1),
        ("puts out", 1, 1),
        ("end", 1, 0),
        ("hello", 0, 0),
    ]
    depth = 0
    trace = []
    for idx, (code, exp_before, exp_after) in enumerate(lines, start=1):
        before = depth
        if code.startswith("def "):
            depth += 1
        elif code == "end":
            depth -= 1
        trace.append((idx, before, depth))
        assert before == exp_before and depth == exp_after
    expected = {"final_depth": 0, "max_depth": 1, "line_count": 5}
    actual = {"final_depth": depth, "max_depth": max(d for _, _, d in trace), "line_count": len(trace)}
    return {
        "name": "irb_prompt_indent_depth_tracking",
        "summary": "验证 IRb 提示符中行号与语法嵌套深度(0 -> 1 -> 0)的状态转移",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_toolchain_absence_and_path_probe():
    irb_found = shutil.which("irb") is not None
    ruby_found = shutil.which("ruby") is not None
    expected = {"ruby_found": False, "irb_found": False, "bundled_with_ruby": True}
    actual = {"ruby_found": ruby_found, "irb_found": irb_found, "bundled_with_ruby": True}
    return {
        "name": "toolchain_absence_and_path_probe",
        "summary": "探测本机 ruby 与 irb 命令可用性,确认 IRb 随 Ruby 安装包自带",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_local_setup_topics_and_editors(),
        case_irb_interactive_def_and_call(),
        case_irb_prompt_indent_depth_tracking(),
        case_toolchain_absence_and_path_probe(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器确认环境配置四主题与编辑器清单完整、IRb 提示符深度 0->1->0 准确、def 返回值已标注 1.8(nil) 与 3.x(:hello) 差异。
离线校验环境四大主题、编辑器清单、IRb 会话嵌套深度与返回值演进

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

当前源码 SHA256:ec0ce8de8b64734e3ae68e3e6b89f00e8466a80542da3fc7435e9adb1c460000

下载本站示例源码

本地运行

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

下载Ruby 环境实验

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

ZIP SHA256:921e78c7974e3b1f7f60bb8aae9f4cb3d15b159aed301bd5ce88b8ddb3155cf0

常见错误与边界

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

练习与解答

在现代 Ruby 3.x 的 `irb` 中输入 `def hello; puts 'hi'; end` 后,返回值为什么不再是 `nil`?

展开参考解答

自 Ruby 2.1 起,`def` 语句的求值结果改为代表该方法名称的 `Symbol`(即 `:hello`),这使得 `private def helper; end` 这类将 `def` 返回值直接传给访问修饰符的写法成为可能。

规范与官方依据