关于 ruby
面向 Ruby 开发者的语言技能,涵盖错误处理、现代 Ruby 惯用法和性能建议,并通过示例与参考资料介绍 Ruby 3.x+ 特性及优化。
主要功能
- 01异常与结果对象模式
- 02Ruby 3.x+ 语言特性
- 03枚举与字符串性能技巧
- 04Ruby 惯用编码规范
- 05性能分析与调优指南
适用场景
- 01为应用选择错误处理方式
- 02在代码库中使用现代 Ruby 语法
- 03减少集合处理中的内存分配
- 04开发时检查 Ruby 编码规范
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ el-feo/ ai-context --skill ruby安装后在 Claude Code 中输入/ruby确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/error_handling.mdmodern_ruby.mdperformance.md详细介绍
Ruby 语言技能
错误处理约定
Weirich raise/fail 约定
首次抛出异常时使用 fail,仅在重新抛出时使用 raise:
def process(order)
fail ArgumentError, "Order cannot be nil" if order.nil?
begin
gateway.charge(order)
rescue PaymentError => e
logger.error("Payment failed: #{e.message}")
raise # re-raise with raise
end
end
自定义异常层次结构
将领域异常归入一个基类错误:
module MyApp
class Error < StandardError; end
class PaymentError < Error; end
class InsufficientFundsError < PaymentError; end
end
# Rescue at any granularity:
rescue MyApp::InsufficientFundsError # specific
rescue MyApp::PaymentError # category
rescue MyApp::Error # all app errors
用于预期失败的结果对象
对于预期的失败路径,使用结果对象而非异常:
class Result
attr_reader :value, :error
def self.success(value) = new(value: value)
def self.failure(error) = new(error: error)
def initialize(value: nil, error: nil) = (@value, @error = value, error)
def success? = error.nil?
def failure? = !success?
end
由调用方提供回退处理
让调用方通过代码块定义错误处理方式:
def fetch_user(id, &fallback)
User.find(id)
rescue ActiveRecord::RecordNotFound => e
fallback ? fallback.call(e) : raise
end
user = fetch_user(999) { |_| User.new(name: "Guest") }
完整模式和重试策略请参阅 references/error_handling.md。
现代 Ruby(3.x+)
模式匹配
case response
in { status: 200, body: { users: [{ name: }, *] } }
"First user: #{name}"
in { status: (400..), error: message }
"Error: #{message}"
end
# Find pattern
case array
in [*, String => str, *]
"Found string: #{str}"
end
# Pin operator
expected = 200
case response
in { status: ^expected, body: }
process(body)
end
其他 3.x+ 特性
# Endless methods (3.0+)
def square(x) = x * x
def admin? = role == "admin"
# Numbered block parameters (2.7+)
[1, 2, 3].map { _1 * 2 }
# Data class - immutable value objects (3.2+)
Point = Data.define(:x, :y)
p = Point.new(x: 1, y: 2)
p.with(x: 3) # => Point(x: 3, y: 2)
# Hash#except (3.0+)
params.except(:password, :admin)
# filter_map (2.7+) - select + map in one pass
users.filter_map { |u| u.email if u.active? }
# tally (2.7+)
%w[a b a c b a].tally # => {"a"=>3, "b"=>2, "c"=>1}
有关 Ractor、fiber 调度器、RBS 类型和高级模式匹配,请参阅 references/modern_ruby.md。
快速提升性能
冻结字符串字面量
# frozen_string_literal: true
# Add to top of every file. Prevents mutation, reduces allocations.
# When you need mutable: String.new("hello") or +"hello"
高效枚举
# each_with_object for building results (avoids intermediate arrays)
totals = items.each_with_object(Hash.new(0)) do |item, hash|
hash[item.category] += item.amount
end
# Lazy enumerables for large/infinite sequences
(1..Float::INFINITY).lazy.select(&:odd?).map { _1 ** 2 }.first(10)
使用记忆化时注意 nil/false
# Simple (only works if result is truthy)
def users = @users ||= User.all.to_a
# Safe (handles nil/false results)
def feature_enabled?
return @feature_enabled if defined?(@feature_enabled)
@feature_enabled = expensive_check
end
字符串构建
# Bad: O(n^2) with +=
result = ""; items.each { |i| result += i.to_s }
# Good: O(n) with <<
result = String.new; items.each { |i| result << i.to_s }
# Best: join
items.map(&:to_s).join
有关 YJIT、GC 调优、基准测试和性能分析工具,请参阅 references/performance.md。
推荐的 Ruby 惯用法
守卫子句
def process(value)
return unless value
return unless value.valid?
# main logic here
end
字面量数组构造器
STATES = %w[draft published archived] # word array
FIELDS = %i[name email created_at] # symbol array
使用 Hash#fetch 获取必需的键
config.fetch(:api_key) # raises KeyError if missing
config.fetch(:timeout, 30) # default value
config.fetch(:handler) { build_handler } # lazy default
安全导航
user&.profile&.avatar_url # returns nil if any link is nil
谓词和 Bang 约定
?后缀:返回布尔值(empty?、valid?、admin?)!后缀:危险版本——会修改接收者或在失败时引发异常(save!、sort!)- 定义 Bang 方法时,始终提供一个非 Bang 替代方法
参考资料
references/modern_ruby.md- 模式匹配、Ractor、fiber 调度器、RBS 类型references/error_handling.md- 异常层次结构、结果对象、重试模式references/performance.md- YJIT、GC 调优、基准测试、性能分析
评论
支持 Markdown