All cheatsheets

Cheatsheets

Ruby

Objects everywhere: blocks, hashes, modules & mixins, iterators, and idioms.

Test yourself

67 entries

Everything is an object6

1.class #=> Integer

Every value is an object — even integers, nil, true, and classes.

3.even? ' hi '.strip

Call methods directly on literals — no wrapper/boxing needed.

obj.respond_to?(:save)

Ask whether an object has a method before calling it.

obj.is_a?(Numeric)

Test class/ancestry membership (alias: kind_of?).

obj.send(:private_method, arg)

Invoke a method by name (incl. private) — metaprogramming.

obj.frozen? obj.freeze

Freeze an object to make it immutable; mutating it then raises FrozenError.

Variables & symbols7

name = 'Ada'

Local variable (lower_snake_case, dynamically typed).

@count = 0

Instance variable — per-object state, defaults to nil.

@@total = 0

Class variable (shared down subclasses; avoid — surprising semantics).

PI = 3.14159

Constant — CamelCase or SCREAMING_CASE; reassigning warns, not errors.

:status :user_id

Symbol — an immutable, interned identifier; the same symbol is one shared object.

a, b = b, a

Parallel assignment — swap or destructure without a temp variable.

a ||= 5

Assign only if currently nil/false — the memoization idiom.

Strings & interpolation7

"Hello, #{name}!"

String interpolation — works only in DOUBLE quotes (and heredocs).

<<~SQL ... SQL

Squiggly heredoc — multi-line string with common leading indentation stripped.

'a' * 3 #=> 'aaa'

Repeat a string with the * operator.

str.gsub(/\d+/, '#')

Global regex substitution; .sub replaces the first match only.

'a,b,c'.split(',')

Split into an array; .join glues an array back into a string.

%w[red green blue] %i[a b]

Word/symbol array literals — ['red',...] and [:a, :b] shorthand.

format('%05.2f', 3.1)

printf-style formatting (alias sprintf / String#%) for numbers and padding.

Arrays & hashes8

[1, 2, 3]

Array literal — ordered, mutable, element types may be mixed.

arr[0] arr[-1] arr[1..3]

Index access; negatives count from the end; ranges slice.

arr << 4 arr.push(5)

Append. .pop/.shift remove from end/front; .unshift prepends.

{ name: 'Ada', age: 36 }

Hash with symbol keys — the modern idiom; `key:` is sugar for `:key =>`.

Hash.new(0)

Hash with a default value — perfect for counting/tallying.

arr.each_with_object({})

Fold into a mutable accumulator (the object is returned).

h.merge(other) h.transform_values { }

Non-destructive merge; bulk-map values/keys.

arr.flatten arr.compact arr.uniq

Flatten nested arrays / drop nils / dedupe.

Blocks, procs, lambdas & iterators10

[1,2,3].each { |x| puts x }

Block — an anonymous chunk of code passed to a method; the core Ruby idiom.

def run; yield 42; end

yield — call the block the method was given, optionally passing arguments.

square = ->(x) { x * x }

Lambda — a Proc that checks arity and whose `return` exits only itself.

arr.map(&:upcase)

Symbol-to-proc — &:sym becomes a block that calls that method on each element.

arr.map { |x| x * 2 }

map — transform every element into a NEW array (the workhorse of functional Ruby).

arr.select { |x| x.even? }

select/filter — keep elements where the block is truthy; reject is the inverse.

arr.reduce(0) { |sum, x| sum + x }

reduce/inject — fold a collection down to a single accumulated value.

users.group_by(&:role)

group_by — bucket elements into a Hash keyed by the block's result.

(1..5).each 3.times arr.each_slice(2)

Ranges and Integer#times are iterators too; each_slice/each_cons chunk.

arr.sort_by { |u| u.age } arr.lazy.map { }.first(5)

Sort by a derived key; lazy enumerators stream over huge/infinite sequences.

Methods & keyword args7

def greet(name) ... end

Method definition — the LAST evaluated expression is the implicit return value.

def create(name:, age: 18)

Keyword arguments — named params; `name:` is required, `age: 18` has a default.

def m(*args, **opts, &blk)

Splat (*) collects positional args, double-splat (**) keywords, & captures the block.

def call(...) = inner(...)

Argument forwarding (3.0+) — pass all args/blocks through verbatim.

def name = @name

Endless method definition (3.0+) — one-expression methods without end.

private def secret; end

Visibility: public (default), private (no explicit receiver), protected.

method(:puts).call('hi')

Methods are objects — grab one with method(:name) and pass it around.

Classes, modules, mixins & attr_accessor8

class User; def initialize(n); @name = n; end; end

Class with a constructor — initialize runs on .new; @ivars hold per-object state.

attr_accessor :name

Generate a reader AND writer for @name — the standard property idiom.

attr_reader :id attr_writer :password

Getter-only / setter-only attribute generators.

class Admin < User

Inheritance — single parent; use super to delegate to it.

module Greetable; def greet; end; end

Module — a bag of methods/constants used as a namespace or a mixin (no instances).

include M / extend M / prepend M

Mixin verbs: include adds INSTANCE methods, extend adds to one object/CLASS, prepend wins over the class.

def self.create; new; end

Class method — define on self (the class object); self.name= needs an explicit self inside the class.

Point = Data.define(:x, :y)

Struct / Data.define — generate a small value class with accessors fast.

Truthiness, control flow & safe nav7

if value # only nil & false are falsy

Truthiness rule: ONLY nil and false are falsy — everything else is truthy.

name = user || 'anonymous'

|| and && return a VALUE (not a boolean) — the idiomatic default/guard.

user&.address&.city

Safe navigation operator &. — call a method only if the receiver is non-nil.

case x; in {role: :admin}; ...; end

case/in — structural pattern matching (3.0+); case/when is the classic switch.

puts 'big' if n > 100

Modifier if/unless/while — trailing condition for one-line guards.

(1..10) === 5 Integer === 5

=== is case-equality (ranges, classes, regexes 'match'); drives case/when.

x.nil? x.zero? arr.empty?

Explicit predicates beat truthiness — say what you mean.

Exceptions, gems & idioms7

begin ... rescue => e ... ensure ... end

Exception handling — rescue catches, ensure always runs (cleanup), else runs on success.

raise ArgumentError, 'must be positive'

Raise an exception; define custom ones by subclassing StandardError.

gem 'rails', '~> 7.1' # Gemfile + bundle install

Gems are Ruby's packages; Bundler pins exact versions per project via Gemfile.lock.

require 'json' require_relative './lib/x'

Load a gem/stdlib by name; require_relative loads a path relative to the current file.

%w[a b a c a].tally

Idiom: count occurrences into a Hash in one pass (replaces a manual Hash.new(0) loop).

value.tap { |v| log(v) }

tap — run a side effect and return the original object (great in chains/debugging).

obj.then { |x| transform(x) }

then/yield_self — pipe a value through a block (functional chaining).