Ruby Cheatsheet

Runtime, Concurrency, and Deploy

Use this Ruby reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Ruby Version Tools

ruby -v
rbenv versions
rbenv local 3.3.0
asdf install ruby 3.3.0
bundle config set path vendor/bundle

Pin the Ruby version for apps so local, CI, and production run the same interpreter line.

Threads

threads = urls.map do |url|
  Thread.new { fetch(url) }
end

results = threads.map(&:value)

MRI Ruby has a global VM lock for Ruby bytecode, so threads help most with I/O waiting. They are still useful for web servers and network-heavy work.

Mutex

lock = Mutex.new
count = 0

threads = 10.times.map do
  Thread.new do
    lock.synchronize { count += 1 }
  end
end
threads.each(&:join)

Use a mutex around shared mutable state. Better yet, minimize shared state and pass immutable values when possible.

Fibers and Schedulers

Fibers are lightweight cooperative execution units. Modern Ruby can use fiber schedulers to make compatible I/O nonblocking, but libraries must support the scheduler model.

fiber = Fiber.new do
  Fiber.yield "pause"
  "done"
end

fiber.resume
fiber.resume

Ractors

Ractors provide an actor-like isolation model for parallel Ruby code, but library support and object-shareability rules are stricter than ordinary threads.

r = Ractor.new { Ractor.receive * 2 }
r.send(21)
r.take

Use Ractors only when the isolation model fits and you have tested dependencies.

Environment and Config

port = Integer(ENV.fetch("PORT", "3000"))
database_url = ENV.fetch("DATABASE_URL")

Validate required environment variables at boot. Convert strings to the types your app expects.

Logging

require "logger"
logger = Logger.new($stdout)
logger.info("job started")
logger.warn("retrying request")

Production apps should log to stdout/stderr in structured enough form for the hosting platform to collect.

Profiling and Benchmarks

require "benchmark"

Benchmark.bm do |x|
  x.report("map") { 100_000.times { [1, 2, 3].map { |n| n * 2 } } }
end

Measure before optimizing. For Rails, inspect SQL, allocations, N+1 queries, cache behavior, and slow external calls.

Deployment Checklist

  • Run tests and linters in CI.
  • Install gems with deployment/frozen settings.
  • Run database migrations explicitly.
  • Precompile assets when the framework needs it.
  • Set RAILS_ENV=production or the app's equivalent environment.
  • Send logs to stdout and errors to monitoring.
  • Restart app workers after code changes.

Common Production Servers

Puma is the common Ruby web server for Rails and Rack apps. Configure workers/threads based on memory, CPU, database pool size, and workload. Keep database pool size at least as large as the maximum threads that can hit the database per process.