Cheatsheets / Ruby

Ruby Cheatsheet

Complete Ruby reference. Hit Ctrl+P to print.

Variables & Types

name = "Alice"Local variable — lowercase or underscore prefix
@name = "Alice"Instance variable — available throughout the object
@@count = 0Class variable — shared across all instances
$global = "shared"Global variable — available everywhere, use sparingly
MAX = 100Constant — uppercase, warns if reassigned
42 / 3.14Integer / Float
"hello" / 'hello'String — double quotes allow interpolation, single are literal
true / falseBoolean
nilAbsence of value (like null)
:name / :statusSymbol — immutable, memory-efficient identifier
[1, 2, 3]Array
{ name: "Alice", age: 30 }Hash (with symbol keys)
(1..10) / (1...10)Inclusive range / exclusive range
x, y = 1, 2Multiple assignment
a, *rest = [1, 2, 3, 4]Splat unpacking — rest = [2, 3, 4]
x.classReturn the class of an object
x.is_a?(Integer)True if x is an Integer (or subclass)
x.nil?True if x is nil

Strings

"Hello, #{name}!"String interpolation — only works in double-quoted strings
"a" + "b" / "a" << "b"Concatenate — << mutates the receiver
"ab" * 3Repeat: "ababab"
s.length / s.sizeNumber of characters
s[0] / s[-1] / s[1..3]Character / last char / substring by range
s.upcase / s.downcaseChange case
s.capitalizeFirst letter uppercase, rest lowercase
s.strip / s.lstrip / s.rstripStrip whitespace from both / left / right
s.chomp / s.chopRemove trailing newline / remove last character
s.include?("sub")True if substring found
s.start_with?("pre") / s.end_with?("suf")Check prefix / suffix
s.index("sub")First index of substring (nil if not found)
s.split(",") / s.splitSplit on delimiter / split on whitespace
["a","b"].join(", ")Join array into string
s.gsub("a", "b")Replace all occurrences
s.gsub(/\d+/, "N")Replace all regex matches
s.sub("a", "b")Replace first occurrence only
s.match?(/pattern/)True if regex matches
s.chars / s.bytesArray of characters / bytes
s.to_i / s.to_f / s.to_symConvert to integer / float / symbol
42.to_s / 3.14.to_sConvert to string
<<~HEREDOC ... HEREDOCHeredoc — squiggly (~) strips leading whitespace

Arrays & Hashes

arr = [1, 2, 3]Array literal
arr.push(4) / arr << 4Append to end
arr.pop / arr.shiftRemove and return last / first element
arr.unshift(0)Prepend element
arr.first / arr.lastFirst / last element
arr.first(3) / arr.last(3)First / last N elements
arr.length / arr.size / arr.countNumber of elements
arr.include?(val)True if value exists
arr.flatten / arr.flatten(1)Flatten nested arrays / one level deep
arr.compactRemove nil values
arr.uniqRemove duplicates
arr.sort / arr.sort_by { |x| x.name }Sort / sort by key
arr.reverseReturn reversed array
arr.min / arr.max / arr.sum / arr.minmaxMin / max / sum / [min, max]
arr.map { |x| x * 2 }Transform each element — returns new array
arr.select { |x| x > 2 }Filter — returns matching elements
arr.reject { |x| x > 2 }Filter — returns non-matching elements
arr.reduce(0) { |sum, x| sum + x }Fold to single value
arr.each_with_index { |x, i| }Iterate with index
arr.each_with_object({}) { |x, h| h[x] = x**2 }Iterate, building an accumulator
arr.zip([4,5,6])Pair up elements: [[1,4],[2,5],[3,6]]
arr.take(3) / arr.drop(3)First N / skip first N elements
arr.any? { |x| x > 2 } / arr.all? { |x| x > 0 } / arr.none? { |x| x < 0 }Any / all / none match predicate
arr.flat_map { |x| [x, x*2] }Map then flatten one level
hash = { name: "Alice", age: 30 }Hash with symbol keys
hash[:name] / hash["key"]Access by symbol / string key
hash[:name] = "Bob"Set or update key
hash.fetch(:name) / hash.fetch(:name, "default")Fetch — raises KeyError or returns default if missing
hash.key?(:name) / hash.value?("Alice")Check key / value existence
hash.keys / hash.valuesArray of keys / values
hash.merge(other) / hash.merge!(other)Merge — merge! mutates receiver
hash.select { |k, v| v > 1 }Filter key-value pairs
hash.map { |k, v| [k, v * 2] }.to_hTransform values into new hash
hash.each { |k, v| }Iterate key-value pairs
hash.delete(:name)Remove key and return its value

Control Flow

if x > 0 ... elsif x < 0 ... else ... endif / elsif / else — end closes the block
puts "positive" if x > 0Inline if (modifier form)
unless x.nil? ... endunless = if not
puts "present" unless x.nil?Inline unless
x > 0 ? "pos" : "neg"Ternary operator
case x\nwhen 1 then "one"\nwhen 2, 3 then "two or three"\nelse "other"\nendcase/when — uses === for comparison
case x\nwhen String then "string"\nwhen Integer then "int"\nendcase with type matching
x = value || "default"Return x if truthy, else default (only nil and false are falsy)
x ||= "default"Assign default if x is nil or false
x&.methodSafe navigation — call method only if x is not nil
while x > 0 ... endLoop while condition is true
until x == 0 ... enduntil = while not
loop do ... break if condition ... endInfinite loop with explicit break
5.times { |i| }Repeat N times
1.upto(5) { |i| } / 5.downto(1) { |i| }Iterate range up / down
(1..5).each { |i| }Iterate over range
next / break / redoSkip iteration / exit loop / restart iteration

Methods

def greet(name)\n "Hello, #{name}!"\nendMethod — last expression is implicitly returned
def greet(name = "World")Default parameter
def fn(*args)Splat — collects extra positional args as array
def fn(**opts)Double splat — collects keyword args as hash
def fn(*args, **opts, &block)Accept any combination including a block
def greet(name:, greeting: "Hello")Keyword arguments with optional default
fn(name: "Alice")Call with keyword arguments
return valueExplicit return — not usually needed
def valid?\ndef save!Convention: ? for predicates, ! for mutating/dangerous methods
private / protected / publicVisibility modifiers — apply to methods below them
private def helperInline visibility on a single method (Ruby 2.1+)
method(:name) / obj.respond_to?(:name)Get method object / check if method exists

Classes & Modules

class Dog < Animal\n def initialize(name)\n @name = name\n end\nendClass inheriting Animal with constructor
dog = Dog.new("Rex")Instantiate object
dog.name / dog.name = "Max"Getter / setter
attr_reader :nameGenerate getter only
attr_writer :nameGenerate setter only
attr_accessor :name, :ageGenerate both getter and setter
def self.create(name)\n new(name)\nendClass method (factory pattern)
super / super(args)Call same method on parent class
selfCurrent object — the receiver of the current method
dog.instance_of?(Dog)True if exactly Dog (not subclass)
dog.is_a?(Animal)True if Dog or any ancestor
module Greetable\n def greet = "Hello!"\nendModule — namespace and mixin container
include GreetableMix module into instances (adds instance methods)
extend GreetableMix module into the class itself (adds class methods)
prepend GreetableLike include but inserted before the class in method lookup
Comparable / EnumerableBuilt-in modules — include to get <=>, sort, min/max etc.

Blocks, Procs & Lambdas

[1,2,3].each { |x| puts x }Block with braces — convention for single-line
[1,2,3].each do |x|\n puts x\nendBlock with do/end — convention for multi-line
def run\n yield\nendyield — calls the block passed to the method
def run\n yield(42) if block_given?\nendyield with argument, guard with block_given?
def run(&block)\n block.call(42)\nendCapture block as explicit Proc parameter
double = Proc.new { |x| x * 2 }Proc — block as an object
double = proc { |x| x * 2 }Shorthand Proc.new
double = lambda { |x| x * 2 }Lambda — strict argument count, own scope for return
double = ->(x) { x * 2 }Lambda stabby syntax (preferred)
double.call(5) / double.(5) / double[5]Call a Proc or Lambda
[1,2,3].map(&method(:puts))Convert method to block with & and method()
[1,2,3].map(&:to_s)Symbol#to_proc — shorthand for { |x| x.to_s }
fn = ->(x, y) { x + y }\nadd = fn.curry.(1)Curry — partially apply arguments