Skip to content
AgileLogics

Ruby Cheat Sheet

Learn Ruby from the basics →

Variables & Types

name = "Ada"
Assign a variable (no keyword, no type)
MAX_USERS = 100
Constant (starts with a capital letter)
:active
Symbol — a lightweight, immutable name
nil
The absence of a value
42.class # => Integer
Every value is an object with a class
"42".to_i / Integer("42")
Lenient vs strict string-to-integer conversion

Strings

"Hello, #{name}!"
Interpolation (double quotes only)
s.upcase / s.downcase / s.capitalize
Change case
s.strip / s.chomp
Trim whitespace / remove trailing newline
s.split(",")
Split into an array
s.include?("Ru")
Substring check
s.gsub(/\d/, "#")
Replace every regex match

Control Flow

if x > 0 ... elsif x < 0 ... else ... end
Conditional
puts "hi" if ready
Modifier if
unless done ... end
Inverse of if
case grade when (90..) then "A" else "B" end
case/when with ranges
3.times { |i| puts i }
Repeat a fixed number of times
while n > 0 ... end
While loop

Arrays & Hashes

nums = [1, 2, 3]
Array literal
nums << 4
Append to an array
nums.map { |n| n * 2 }
Transform every element
nums.select(&:even?)
Keep matching elements
nums.sum / nums.reduce(:+)
Combine into one value
user = { name: "Ada", age: 36 }
Hash with symbol keys
user.fetch(:email, "none")
Look up with a default
user.each { |key, value| ... }
Iterate a hash

Methods & Blocks

def greet(name, greeting: "Hi") = "#{greeting}, #{name}"
Endless method with a keyword argument
def total(*nums) nums.sum end
Any number of positional arguments
yield value if block_given?
Call the block passed to a method
square = ->(x) { x * x }; square.(4)
Lambda
empty? / sort!
Naming: ? returns a boolean, ! is the "dangerous" version

Classes & Modules

class User; attr_reader :name; def initialize(name); @name = name; end; end
Class with a constructor and reader
class Admin < User
Inheritance
module Greetable; def greet = "Hi, #{name}"; end
Module of reusable methods
include Comparable
Mix a module into a class
Point = Data.define(:x, :y)
Immutable value object (Ruby 3.2+)

Errors

begin ... rescue ZeroDivisionError => e ... ensure ... end
Handle an exception
raise ArgumentError, "age must be positive"
Raise an exception
class InsufficientFunds < StandardError; end
Custom exception class
user&.name
Safe navigation — nil instead of NoMethodError

Tooling

ruby app.rb
Run a script
irb
Interactive Ruby console
bundle init / bundle add rspec
Create a Gemfile / add a gem
bundle exec rspec
Run a command with the project's gem versions
bundle exec rubocop -a
Lint and auto-correct style