← 返回目录

第一章:环境安装

安装 Ruby 3.3,配置开发环境

1. 安装 Ruby 3.3

Ruby 3.3 带来了 YJIT 性能改进和更好的解析器 Prism。根据你的操作系统选择对应的安装方式。

macOS(Homebrew)

macOS 自带系统 Ruby(版本较旧),推荐用 Homebrew 安装最新版:

brew install ruby

如果需要管理多个 Ruby 版本,推荐使用 rbenv:

brew install rbenv ruby-build
rbenv install 3.3.0
rbenv global 3.3.0

# 将 rbenv 初始化添加到 shell 配置
echo 'eval "$(rbenv init -)"' >> ~/.zshrc
source ~/.zshrc

提示:rbenv 通过 shims 目录拦截 Ruby 命令,实现版本切换。每次安装新 gem 后运行 rbenv rehash(rbenv 0.9.0+ 已自动执行)。

Ubuntu / Debian

Ubuntu 官方源通常版本较旧,推荐用 rbenv 安装:

# 方式一:系统包(版本可能不是最新)
sudo apt install ruby-full

# 方式二:rbenv(推荐,可安装任意版本)
sudo apt install git curl libssl-dev libreadline-dev zlib1g-dev
curl -fsSL https://github.com/rbenv/rbenv-installer/raw/HEAD/bin/rbenv-installer | bash
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc

rbenv install 3.3.0
rbenv global 3.3.0

Windows

Windows 推荐使用 RubyInstaller,它捆绑了 MSYS2 开发工具链:

# 从 https://rubyinstaller.org/ 下载 Ruby+Devkit 版本
# 安装时勾选 "Add Ruby executables to your PATH"
# 安装完成后在弹出的窗口中选择 MSYS2 and MINGW 开发工具链(选项 3)

验证安装

$ ruby -v
ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [arm64-darwin23]

$ gem -v
3.5.3

🔄 版本检查命令对比

Ruby ruby -v
Python python3 --version
Node.js node -v
PHP php -v

2. IRB 交互式环境

IRB(Interactive Ruby)是 Ruby 自带的交互式 REPL,可以逐行执行 Ruby 代码,非常适合快速实验和调试。

$ irb
irb(main):001> 1 + 2
=> 3
irb(main):002> "Hello, Ruby".upcase
=> "HELLO, RUBY"
irb(main):003> [1, 2, 3].map { |n| n * 10 }
=> [10, 20, 30]
irb(main):004> { name: "Ruby", year: 1995 }.keys
=> [:name, :year]
irb(main):005> exit

Ruby 3.x 的 IRB 内置了语法高亮、自动补全和多行编辑支持。还可以用 irb --simple-prompt 使用精简提示符。

IRB 是 Ruby 的 REPL:类似于 Python 的交互式解释器和 Node.js 的 REPL。在 IRB 中,每个表达式的返回值会自动显示(以 => 开头),无需手动 print。

3. 安装 Bundler

Bundler 是 Ruby 的依赖管理工具,通过 Gemfile 声明项目依赖,确保团队使用一致的 gem 版本。Ruby 2.6+ 已默认捆绑 Bundler。

# 如果系统未自带或需要更新
gem install bundler

# 确认版本
bundler -v

初始化项目

mkdir my-ruby-project && cd my-ruby-project
bundle init

这会生成一个 Gemfile,编辑它来添加依赖:

source "https://rubygems.org"

gem "httparty", "~> 0.21"
gem "nokogiri", "~> 1.16"
gem "pry", group: :development
# 安装所有依赖
bundle install

# 运行项目中的 Ruby 脚本(自动加载 Bundler 环境)
bundle exec ruby app.rb

提示:Gemfile.lock 记录了精确的 gem 版本,应提交到版本控制。团队成员运行 bundle install 会安装相同版本,避免 "在我机器上能跑" 的问题。

🔄 包管理器对比

语言 工具 配置文件 锁文件
Ruby Bundler Gemfile Gemfile.lock
Node.js npm package.json package-lock.json
Python pip requirements.txt
PHP Composer composer.json composer.lock

4. Hello World

创建一个 hello.rb 文件,体验 Ruby 的基本语法:

name = "Ruby"
version = 3.3
features = ["YJIT", "Pattern Matching", "Ractor", "Fiber Scheduler"]

puts "Hello, #{name} #{version}!"

puts "Ruby 3.x 核心特性:"
features.each_with_index do |feature, i|
  puts "  #{i + 1}. #{feature}"
end

def greet(who)
  "欢迎学习 #{who}!"
end

puts greet("Ruby 3.3")

3.times { puts "Ruby is fun!" }

numbers = [1, 2, 3, 4, 5]
squares = numbers.map { |n| n ** 2 }
puts "平方:#{squares.inspect}"
$ ruby hello.rb
Hello, Ruby 3.3!
Ruby 3.x 核心特性:
  1. YJIT
  2. Pattern Matching
  3. Ractor
  4. Fiber Scheduler
欢迎学习 Ruby 3.3!
Ruby is fun!
Ruby is fun!
Ruby is fun!
平方:[1, 4, 9, 16, 25]

语法要点速记:

  • • 不需要分号结尾,换行即为语句结束
  • • 双引号字符串支持插值 #{expression},单引号不支持
  • • 一切皆对象:数字、字符串、niltrue/false 都是对象
  • • 方法调用可省略括号:puts "hello" 等同于 puts("hello")
  • • 方法的最后一个表达式自动作为返回值(隐式 return)

🔄 运行方式对比

Ruby ruby hello.rb
Python python hello.py
PHP php hello.php
Java javac Hello.java && java Hello

Ruby 和 Python 一样是解释型语言,无需编译步骤。Ruby 3.x 的 YJIT 即时编译器可显著提升运行时性能。

5. VS Code 配置

VS Code 是 Ruby 开发的主流编辑器。安装以下扩展可以获得出色的开发体验:

🧠

Ruby LSP

Shopify 出品的官方语言服务器,提供智能补全、跳转定义、内联诊断、代码格式化。

Shopify.ruby-lsp
🔍

Solargraph

基于 YARD 文档的智能感知引擎,类型推断、文档提示和代码补全。

castwide.solargraph
🐛

VSCode rdbg

Ruby 官方调试器 debug.gem 的 VS Code 适配器,支持断点、变量查看、调用栈。

KoichiSasada.vscode-rdbg

推荐在项目中添加 .vscode/settings.json

{
    "editor.formatOnSave": true,
    "[ruby]": {
        "editor.defaultFormatter": "Shopify.ruby-lsp",
        "editor.tabSize": 2
    },
    "rubyLsp.formatter": "auto",
    "rubyLsp.yjit": true
}

Ruby LSP vs Solargraph:Ruby LSP 是 Shopify 维护的新一代 LSP,更轻量且与 Ruby 3.x 兼容更好。Solargraph 功能更成熟但依赖 YARD 注解。两者可以同时安装,按需选择默认 LSP。

6. 本章要点

🛠️ 安装 Ruby

macOS 用 brew install ruby 或 rbenv,Ubuntu 用 rbenv,Windows 用 RubyInstaller。用 ruby -v 验证安装。

💎 IRB 交互环境

输入 irb 进入交互模式,逐行执行代码,表达式结果自动显示。Ruby 3.x 内置语法高亮和自动补全。

📦 Bundler 依赖管理

bundle init 创建 Gemfile,编辑后 bundle install 安装依赖。Gemfile.lock 锁定版本,确保环境一致。

📝 基本语法

无需分号,#{} 字符串插值,一切皆对象,方法隐式返回最后一个表达式的值,括号可选。

💻 开发工具

VS Code + Ruby LSP 提供智能补全,Solargraph 提供类型推断,rdbg 支持断点调试。

🚀 Hello World

创建 .rb 文件,用 ruby filename.rb 运行。Ruby 是解释型语言,无需编译。