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 scheduler、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 scheduler、RBS の型references/error_handling.md- 例外階層、結果オブジェクト、リトライパターンreferences/performance.md- YJIT、GC のチューニング、ベンチマーク、プロファイリング
コメント
Markdown 対応