SkilVaultSign inStart free

Catalogue / idiomatic-ruby

idiomatic-ruby

Older skill: source not recordedSignedGuides the writing, reviewing, and refactoring of idiomatic Ruby — object modeling with classes and modules, blocks and lambdas, Enumerable pipelines, restrained metaprogramming, exception design, RSpec testing, and threads. Triggers when the user asks for Ruby or Ruby on Rails code, gem or Rake wor…
---
name: idiomatic-ruby
description: Guides the writing, reviewing, and refactoring of idiomatic Ruby — object modeling with classes and modules, blocks and lambdas, Enumerable pipelines, restrained metaprogramming, exception design, RSpec testing, and threads. Triggers when the user asks for Ruby or Ruby on Rails code, gem or Rake work, or Ruby debugging; not for other languages.
---

Idiomatic Ruby

Use this skill whenever you are asked to write, review, refactor, or debug Ruby. Aim for code a seasoned Rubyist would accept in a pull request: small objects, honest names, blocks where they read well, and metaprogramming only when plain code cannot do the job.

Ground yourself first

Before writing anything, establish the context:

  1. Look for a Gemfile, .ruby-version, or gems.rb to learn the Ruby version and whether the project uses Rails, Bundler, or Rake.
  2. Prefer the standard library and already-listed gems over inventing new dependencies. If a new gem seems necessary, propose it and wait for the user to agree before touching the Gemfile or lockfile.
  3. Match the style already present in the file you are editing — quoting, spacing, naming — over imposing your own preferences.
  4. When a task is ambiguous about version or framework, ask rather than assume.

Model the domain with classes and modules

Expose state through attr_reader and friends instead of raw accessors when you can, keep constructors simple, and push validation and formatting into private methods:

class Playlist
  attr_reader :name, :tracks

  def initialize(name)
    @name = name
    @tracks = []
  end

  def add(track)
    tracks << track
    self
  end

  def total_duration
    tracks.sum(&:duration)
  end

  def to_s
    "#{name}: #{tracks.size} tracks, #{total_duration}s"
  end

  private

  def playable?(track)
    track.respond_to?(:duration) && track.duration.positive?
  end
end

Use inheritance sparingly and call super when a subclass extends a constructor:

class SharedPlaylist < Playlist
  def initialize(name, owner)
    super(name)
    @owner = owner
  end
end

Use modules to share behavior across unrelated classes and to namespace groups of classes. Implement <=> and include Comparable when objects have a natural ordering:

module Sluggable
  def to_slug
    to_s.downcase.strip.gsub(/\s+/, "-")
  end
end

class Track
  include Comparable

  attr_reader :title, :duration

  def initialize(title, duration)
    @title = title
    @duration = duration
  end

  def <=>(other)
    duration <=> other.duration
  end
end

Hand behavior around with blocks

Accept a block with yield, guard with block_given?, and capture explicitly with &block only when you need to store or forward it:

def timed(label)
  started = monotonic_clock
  result = yield
  log.info("#{label} took #{monotonic_clock - started}s")
  result
end

timed("import") { importer.run }

Know the callable objects and pick deliberately:

double = ->(n) { n * 2 }      # lambda: strict arity, returns like a method
doubler = proc { |n| n * 2 }  # proc: lenient arity, returns from the enclosing method
doubler.call(21)              # => 42, no complaint about missing arguments

Reach for the symbol-to-proc shorthand whenever the operation is a single method call: tracks.map(&:title) instead of tracks.map { |t| t.title }.

Treat collections as pipelines

Reach for Enumerable before writing manual loops. Reach for map, select, reject, find, sum, group_by, partition, each_with_object, and reduce — and use lazy when a pipeline over a large or infinite range would otherwise build a huge intermediate array:

reports.partition { |r| r.complete? }
errors = lines.each_with_object([]) { |line, acc| acc << line if line.start_with?("ERROR") }
(1..Float::INFINITY).lazy.select { |n| n % 7 == 0 }.first(5)

Give your own classes full collection powers by defining each and including Enumerable:

class ReadingList
  include Enumerable

  def initialize
    @books = []
  end

  def <<(book)
    @books << book
    self
  end

  def each
    @books.each { |book| yield book }
  end
end

list = ReadingList.new
list << "Hyperion" << "Dune"
list.select { |b| b.length > 4 }
list.sort
list.count

Use metaprogramming reluctantly

Prefer plain methods. When generated code genuinely removes duplication, use define_method:

class Order
  STATES = %w[pending paid shipped closed].freeze

  STATES.each do |state|
    define_method("#{state}?") { @state == state }
  end
end

If you must intercept unknown messages, always implement respond_to_missing? alongside method_missing, and prefer public_send over send so you never invoke private methods by accident:

class ApiClient
  def initialize(http)
    @http = http
  end

  def method_missing(name, *args, &block)
    return @http.public_send(name, *args, &block) if @http.respond_to?(name)
    super
  end

  def respond_to_missing?(name, include_private = false)
    @http.respond_to?(name) || super
  end
end

Never reopen core classes like String or Hash to add methods for everyone. If an extension is truly justified, scope it with refine and activate it with using inside the one file that needs it.

Fail loudly and deliberately

Rescue the most specific exception first, keep ensure for cleanup, and cap retry with a counter so a persistent failure cannot loop forever:

class AppError < StandardError; end

class PaymentError < AppError
  attr_reader :invoice_id

  def initialize(invoice_id, message)
    super(message)
    @invoice_id = invoice_id
  end
end

attempts = 0
begin
  gateway.charge(invoice)
rescue GatewayTimeout
  attempts += 1
  retry if attempts < 3
  raise
ensure
  gateway.close
end

Build a small error hierarchy rooted in your own StandardError subclass so callers can rescue your failures without swallowing Ruby's internal errors. When a method should not raise, return an outcome object instead:

class Outcome
  def self.ok(value)   = new(value: value)
  def self.err(reason) = new(error: reason)

  attr_reader :value, :error

  def initialize(value: nil, error: nil)
    @value = value
    @error = error
  end

  def ok?    = error.nil?
  def error? = !ok?
end

Prove it with RSpec

Describe behavior, not implementation. Use subject, let, and factory helpers to keep examples readable; use test doubles for external services and assert on interactions:

RSpec.describe InvoiceMailer, "#deliver" do
  subject(:deliver) { described_class.deliver(invoice) }

  let(:invoice) { build(:invoice, total: 2500) }
  let(:gateway) { instance_double(MailGateway) }

  before do
    allow(MailGateway).to receive(:new).and_return(gateway)
    allow(gateway).to receive(:send_invoice)
  end

  it "hands the invoice to the gateway" do
    deliver
    expect(gateway).to have_received(:send_invoice).with(invoice)
  end

  it "marks the invoice as sent" do
    expect { deliver }.to change { invoice.sent? }.from(false).to(true)
  end
end

Cover both the success path and at least one failure path for anything that can fail.

Go concurrent only when there is a reason

Default to sequential code. When work is genuinely independent and slow, distribute it across threads, guard shared state with a Mutex, and drain a Queue so workers pull their own items:

work = Queue.new
paths.each { |p| work << p }

results = []
lock = Mutex.new

workers = 4.times.map do
  Thread.new do
    until work.empty?
      outcome = resize(work.pop)
      lock.synchronize { results << outcome }
    end
  end
end
workers.each(&:join)

For I/O-bound work, mention the async gem as an option; for true parallelism without shared mutable state on Ruby 3+, mention Ractor — but explain the trade-offs rather than defaulting to either.

Hard rules — things you must NOT do

  • Do not rescue an exception and continue silently. Every rescue must either handle the failure meaningfully, log it, or re-raise it.
  • Do not monkey-patch core classes at the top level; scoped refinements are the only acceptable form of core extension.
  • Do not feed user-supplied or otherwise untrusted strings into eval, instance_eval, or dynamic method dispatch. Look up whitelisted methods instead.
  • Do not read, copy, or echo secrets — API keys, credential files, or environment variables holding them — into source files, test fixtures, logs, or anywhere the user has not explicitly requested.
  • Never download code from the network and execute it.
  • Do not install gems system-wide, run administrative package commands, modify the lockfile, publish a gem, or take any externally visible or hard-to-reverse action (including deleting files or rewriting version control history) without stating what you intend and getting explicit confirmation from the user first.
  • Do not add a dependency when the standard library or an existing gem already solves the problem.

Final check

Before presenting the code, re-read it and confirm: no swallowed exceptions, no unneeded dependencies, no global monkey patching, tests covering failure paths, and style consistent with the surrounding project. Only then show the result.