Ruby Cheatsheet
Tools, Testing, and Style
Use this Ruby reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Gems and Bundler
gem install bundler bundle init bundle add minitest bundle install bundle exec ruby app.rb
Gemfile declares dependencies. Gemfile.lock records exact versions. Use bundle exec so commands run with the versions from the lockfile.
Project Layout
my_app/
Gemfile
lib/
my_app.rb
my_app/user.rb
test/
user_test.rbSmall scripts can be one file. Reusable libraries usually put code under lib/ and tests under test/ or spec/.
Minitest
require "minitest/autorun" require_relative "../lib/calculator" class CalculatorTest < Minitest::Test def test_adds_numbers assert_equal 5, Calculator.add(2, 3) end end
Minitest ships with Ruby. It is a good default for fundamentals and small libraries.
RSpec Shape
RSpec.describe Calculator do it "adds numbers" do expect(Calculator.add(2, 3)).to eq(5) end end
RSpec is common in Rails apps and larger Ruby teams. It is expressive, but adds a dependency and its own DSL.
Style Conventions
snake_case_method CamelCaseClass SCREAMING_SNAKE_CASE = true valid? # predicate method save! # stricter or mutating version by convention name= # writer method
Use two spaces for indentation. Prefer clear method names, small objects, and direct Enumerable chains.
Mutation vs Non-Mutation
name = " ruby " name.strip # returns new string name # still " ruby " name.strip! # mutates name, returns nil if no change arr.sort # new sorted array arr.sort! # sort in place
Bang methods often mutate or raise more aggressively. Always check the documentation for the exact contract.
Debugging
p value # inspect to stdout puts value.inspect warn "message" # stderr caller.first # current call location raise "stop here" # quick breakpoint-like stop
For real projects, use the debug gem available in modern Ruby versions.
Performance Basics
- Use
String#<<or an array plusjoinfor repeated string building. - Use
Setfor many membership checks. - Avoid repeated
array.include?inside large loops when a hash or set would do. - Prefer streaming files line by line with
File.foreachfor large files. - Measure with
Benchmarkbefore rewriting clear code.
require "benchmark" puts Benchmark.measure { 100_000.times { "ruby".upcase } }