Ruby Cheatsheet - Ruby Syntax & Methods Reference
Essential Ruby syntax for daily development, organized by category from basics to advanced features like blocks, modules, and metaprogramming. Copy directly when coding.
Back to Languages基础语法 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"\nendif 条件语句
puts "positive" if x > 0后置 if,简洁写法
unless x > 0\n puts "not positive"\nendunless 条件,相当于 if !
case x\nwhen 1 then "one"\nelse "other"\nendcase 多分支匹配
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\nendwhile 循环
until x == 0\n x -= 1\nenduntil 循环,相当于 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?\nendyield 调用传入的块
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_methodself 表示当前对象,定义类方法
class << self\nend单例类,定义类方法
异常处理 Exception 7
begin\n risky_call\nrescue\n "error"\nendbegin-rescue 捕获异常
rescue SpecificError => e捕获指定类型的异常
ensure\n cleanup\nendensure 保证执行清理代码
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".upcaseString#upcase 大写
"hello".split("")String#split 分割字符串
"hello".gsub(/l/, "L")String#gsub 全局替换
arr.flattenArray#flatten 展开嵌套数组
arr.uniqArray#uniq 去重
块与迭代器 Blocks & Iterators 7
[1, 2].each { |n| puts n }each 遍历每个元素
[1, 2].each do |n|\n puts n\nenddo...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 按条件分组为哈希
💡 Tips
- Everything is an object in Ruby, including nil and numbers
- each is the most common iterator, map for transformation, select for filtering
- Symbols :symbol are immutable and unique, ideal for hash keys
- attr_accessor automatically generates getter and setter methods
- Blocks are Ruby's most powerful feature, do...end and {} are equivalent