Ruby 环境
总览本地 Ruby 开发环境设置的四大主题、常见跨平台与 Windows 编辑器选型,以及交互式 Ruby(IRb)会话的基本用法。
学完这一章,你能够
- 总览本地 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 会话嵌套深度与返回值演进
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
自 Ruby 2.1 起,`def` 语句的求值结果改为代表该方法名称的 `Symbol`(即 `:hello`),这使得 `private def helper; end` 这类将 `def` 返回值直接传给访问修饰符的写法成为可能。