Ruby Cheatsheet

Errors, I/O, and Stdlib

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

Exceptions

begin
  value = Integer(input)
rescue ArgumentError => e
  value = nil
ensure
  cleanup
end

Rescue the narrow error you expect. Avoid bare rescue in library code because it can hide serious failures.

Raising Errors

raise ArgumentError, "amount must be positive" if amount <= 0

class PaymentError < StandardError; end
raise PaymentError, "card declined"

Custom app errors usually inherit from StandardError.

STDIN, STDOUT, and ARGV

name = STDIN.gets&.chomp
puts "Hello, #{name || "friend"}"
warn "debug goes to stderr"

# ruby script.rb input.txt --verbose
file, flag = ARGV

gets reads from standard input. ARGV contains command-line arguments as strings, excluding the Ruby file name.

Fast Input for Exercises

tokens = STDIN.read.split
n = tokens[0].to_i
nums = tokens[1, n].map(&:to_i)

For competitive-style input, read once and parse tokens. Avoid repeated prompts or human-only formatting.

Files

File.read("notes.txt")
File.write("notes.txt", "hello\n")
File.readlines("notes.txt", chomp: true)

File.open("log.txt", "a") do |file|
  file.puts "started"
end

File.foreach("large.log", chomp: true) do |line|
  process(line)
end

The block form closes the file automatically. File.foreach streams large files line by line.

Paths

require "pathname"
path = Pathname.new("data/users.json")
path.basename.to_s
path.dirname
path.extname
path.exist?

JSON

require "json"
obj = JSON.parse('{"name":"Ada"}')
JSON.generate({ ok: true, count: 2 })
JSON.pretty_generate(obj)

Ruby hashes with symbol keys become string keys in JSON output.

CSV

require "csv"
CSV.foreach("users.csv", headers: true) do |row|
  puts row["email"]
end

CSV.generate do |csv|
  csv << ["name", "score"]
  csv << ["Ada", 100]
end

Time and Date

require "date"
require "time"
Time.now
Time.utc(2026, 1, 1)
Time.parse("2026-01-01T12:00:00Z")
Date.today
Date.parse("2026-01-01")

Regular Expressions

email = "ada@example.com"
email.match?(/\A[^@]+@[^@]+\z/)
email[/\A([^@]+)/, 1]  # capture before @
"abc123".gsub(/\d+/, "#")

Use \A and \z for start/end of the whole string. ^ and $ are line anchors.

require_relative

# app/models/user.rb
class User; end

# app/main.rb
require_relative "models/user"

require_relative loads files relative to the current file. It is common in small scripts and exercises.

Useful Standard Library

LibraryUse
jsonJSON parse/generate
csvCSV files
setunique collections
datedates without time zones
timetime parsing/formatting extensions
pathnameobject-oriented filesystem paths
securerandomrandom tokens and UUIDs
uriURL parsing
net/httpHTTP client basics
optparsecommand-line option parsing