Ruby 语法速查表 - Ruby 常用方法大全

Ruby 编程日常开发必备语法都在这里了,从基础语法到高级特性(块、模块、元编程),按类别分类整理,写代码时直接复制。

编程语言·共 69 条命令·最后更新 2026-07-21
返回 编程语言

基础语法 Basics 7

name = "Ruby"
变量赋值,动态类型无需声明
name = "Hello, #{name}"
字符串插值,双引号有效
:symbol
符号,不可变且唯一,适合做哈希键
# 这是单行注释
单行注释以 # 开头
=begin\n注释块\n=end
多行注释块
nil
空值,nil 也是对象
true / false
布尔值,也是对象

数组与哈希 Array & Hash 9

arr = [1, 2, 3]
创建数组
arr << 4
追加元素
arr[0]
访问索引 0 的元素
arr.first / arr.last
第一个 / 最后一个元素
hash = { a: 1, b: 2 }
创建哈希(符号键简写语法)
hash[:a]
访问哈希键值
hash[:c] = 3
设置哈希键值
hash.key?(:a)
检查键是否存在
hash.keys / hash.values
获取所有键 / 值

控制流 Control Flow 10

if x > 0\n puts "positive"\nend
if 条件语句
puts "positive" if x > 0
后置 if,简洁写法
unless x > 0\n puts "not positive"\nend
unless 条件,相当于 if !
case x\nwhen 1 then "one"\nelse "other"\nend
case 多分支匹配
3.times { puts "hi" }
重复执行指定次数
1.upto(5) { |n| puts n }
从 1 递增到 5
5.downto(1) { |n| puts n }
从 5 递减到 1
loop { break if done }
无限循环,需手动 break
while x > 0\n x -= 1\nend
while 循环
until x == 0\n x -= 1\nend
until 循环,相当于 while !

方法定义 Methods 9

def greet(name)\n "Hello, #{name}"\nend
定义方法,最后一行自动返回
def greet(name = "World")
方法参数带默认值
def sum(*args)
splat 运算符,接收可变参数
def method(a:, b:)
关键字参数,顺序无关
return value
显式返回值(可选)
def method\n yield if block_given?\nend
yield 调用传入的块
my_proc = Proc.new { |x| x*2 }
创建 Proc 对象
my_lambda = ->(x) { x*2 }
创建 Lambda(箭头语法)
proc.call(5)
调用 Proc / Lambda

类与模块 Class & Module 10

class MyClass\nend
定义类
attr_accessor :name
自动生成 getter 和 setter
attr_reader :name
只读 getter
attr_writer :name
只写 setter
class Child < Parent
类继承
module MyModule\nend
定义模块
include MyModule
混入模块方法(实例方法)
extend MyModule
混入模块方法(类方法)
self.class_method
self 表示当前对象,定义类方法
class << self\nend
单例类,定义类方法

异常处理 Exception 7

begin\n risky_call\nrescue\n "error"\nend
begin-rescue 捕获异常
rescue SpecificError => e
捕获指定类型的异常
ensure\n cleanup\nend
ensure 保证执行清理代码
raise "error message"
手动抛出异常
raise ArgumentError, "msg"
抛出指定类型的异常
retry
在 rescue 中重试 begin 块
catch(:done) { throw(:done) }
catch/throw 非局部跳转

常用内置方法 Built-in Methods 10

arr.map { |x| x*2 }
Array#map 转换数组
arr.select { |x| x.even? }
Array#select 筛选偶数
arr.reject { |x| x.even? }
Array#reject 排除偶数
arr.reduce(0) { |s, x| s + x }
Array#reduce 归约求和
hash.merge({ c: 3 })
Hash#merge 合并哈希
"hello".upcase
String#upcase 大写
"hello".split("")
String#split 分割字符串
"hello".gsub(/l/, "L")
String#gsub 全局替换
arr.flatten
Array#flatten 展开嵌套数组
arr.uniq
Array#uniq 去重

块与迭代器 Blocks & Iterators 7

[1, 2].each { |n| puts n }
each 遍历每个元素
[1, 2].each do |n|\n puts n\nend
do...end 块,等价于 {}
(1..5).map { |n| n**2 }
map 转换(返回新数组)
[1, 2, 3].select(&:even?)
select 带 &: 简写语法
arr.partition { |x| x.even? }
partition 分为两组 [[偶数], [奇数]]
arr.chunk { |x| x > 0 }
chunk 按条件分组
arr.group_by { |x| x % 3 }
group_by 按条件分组为哈希

💡 提示

  • Ruby 中一切皆对象,包括 nil 和数字
  • each 是最常用的迭代器,map 用于转换,select 用于筛选
  • 符号 :symbol 不可变且唯一,适合做哈希键
  • attr_accessor 自动生成 getter 和 setter
  • 块(block)是 Ruby 最强大的特性,do...end 和 {} 等价