Skip to main content

Ruby Reference

v1.0.0

Quick-reference for Ruby syntax, blocks, modules, gems, and Rails patterns

Searchable cheat sheet for Ruby 3.x — data types, string methods, blocks/procs/lambdas, classes, metaprogramming, and gem management.

How to use
  • Type a keyword like "each", "lambda", or "rescue" to jump to matching entries instantly.
  • Click any entry card to expand a runnable code example — copy and adapt it in your Ruby project.
  • Use the category tabs (e.g. Blocks/Procs/Lambdas, Classes/Modules) to explore related concepts together.
  • Try the Example picker (Simple → Advanced → Pro) to pre-fill a search for common Ruby patterns.

47 entries found

Integer / Float
Data Types

x = 42 y = 3.14

Numeric types — Ruby auto-promotes Integer to Bignum for large values. Underscores allowed for readability.

String
Data Types

s = "hello" s = 'hello'

Double-quoted strings support interpolation and escape sequences. Single-quoted strings are literal.

Symbol
Data Types

:name / :"with spaces"

Immutable, interned identifiers — commonly used as hash keys and method names. Faster comparison than strings.

Array
Data Types

arr = [1, 2, 3] arr = Array.new(5, 0)

Ordered, indexed collection that can hold mixed types.

Hash
Data Types

h = { key: "value" } h = Hash.new(0)

Key-value collection — symbol keys use shorthand syntax, string keys use hash rockets.

Range
Data Types

(1..10) # inclusive (1...10) # exclusive

Represents a sequence between two endpoints — used for iteration, slicing, and case matching.

Nil / Boolean
Data Types

nil true / false

nil is the absence of a value. Only nil and false are falsy — everything else is truthy (including 0).

Interpolation / Concatenation
String Methods

"Hello, #{expr}" str1 + str2 / str1 << str2

Embed expressions in double-quoted strings. Concatenate with + (new string) or << (mutate in place).

gsub / sub
String Methods

str.gsub(pattern, replacement) str.sub(pattern, replacement)

gsub replaces all occurrences, sub replaces only the first. Accepts strings or regex.

split / join
String Methods

str.split(delimiter) arr.join(delimiter)

split breaks a string into an array. join combines array elements into a string.

strip / chomp / chop
String Methods

str.strip / str.chomp / str.chop

strip removes leading/trailing whitespace. chomp removes trailing newline. chop removes last character.

match / scan / =~
String Methods

str.match(regex) str.scan(regex) str =~ regex

match returns MatchData for first match. scan returns all matches as an array. =~ returns index of first match.

freeze / frozen?
String Methods

str.freeze str.frozen?

freeze makes a string immutable. frozen? checks immutability. Frozen string literals can be enabled globally.

map / collect
Array/Hash Methods

arr.map { |x| expr } arr.collect { |x| expr }

Transform each element, returning a new array. map and collect are aliases.

select / reject / filter
Array/Hash Methods

arr.select { |x| condition } arr.reject { |x| condition }

select keeps elements matching the condition. reject removes them. filter is an alias for select.

reduce / inject
Array/Hash Methods

arr.reduce(init) { |acc, x| expr } arr.inject(:+)

Accumulate values into a single result. reduce and inject are aliases.

each_with_object / each_with_index
Array/Hash Methods

arr.each_with_object({}) { |x, h| ... } arr.each_with_index { |x, i| ... }

each_with_object passes an accumulator object. each_with_index provides the current index.

flat_map / flatten
Array/Hash Methods

arr.flat_map { |x| expr } arr.flatten(depth)

flat_map maps then flattens one level. flatten recursively flattens nested arrays.

sort / sort_by / min / max
Array/Hash Methods

arr.sort { |a, b| a <=> b } arr.sort_by { |x| expr }

Sort elements. The spaceship operator (<=>) returns -1, 0, or 1. sort_by is more efficient for complex keys.

group_by / tally / zip
Array/Hash Methods

arr.group_by { |x| expr } arr.tally arr.zip(other)

group_by partitions into a hash of arrays. tally counts occurrences. zip merges arrays element-wise.

Hash — merge / transform
Array/Hash Methods

h1.merge(h2) { |k, v1, v2| ... } h.transform_values { |v| expr }

merge combines hashes (block resolves conflicts). transform_values maps over values in place.

Block (do...end / braces)
Blocks/Procs/Lambdas

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

Blocks are anonymous code chunks passed to methods. Braces for single-line, do...end for multi-line by convention.

yield
Blocks/Procs/Lambdas

def method_name yield(args) if block_given? end

yield transfers control to the block passed to the method. block_given? checks if a block was provided.

Proc
Blocks/Procs/Lambdas

p = Proc.new { |x| expr } p = proc { |x| expr }

Proc is a stored block. Lenient with argument count — extra args are ignored, missing args become nil.

Lambda
Blocks/Procs/Lambdas

l = lambda { |x| expr } l = ->(x) { expr }

Lambda is a strict Proc — enforces arity and return exits to the calling scope (not the enclosing method).

Method objects (&method)
Blocks/Procs/Lambdas

method(:name) [1,2,3].map(&method(:puts))

Convert a method reference into a callable object. & converts Proc/method to a block.

Closure semantics
Blocks/Procs/Lambdas

Blocks, Procs, and Lambdas close over local variables.

All three capture the enclosing scope — changes to captured variables are reflected inside and outside the closure.

Class definition
Classes/Modules

class Name def initialize(args) @field = value end end

Classes use initialize as the constructor. Instance variables start with @.

attr_accessor / attr_reader / attr_writer
Classes/Modules

attr_accessor :name, :age attr_reader :id attr_writer :password

Auto-generate getter and/or setter methods for instance variables.

Inheritance
Classes/Modules

class Child < Parent def method super end end

Single inheritance with < operator. super calls the parent method.

Module (mixin)
Classes/Modules

module Name def method; end end class Foo include Name end

Modules provide mixins (include for instance methods, extend for class methods) and namespacing.

Comparable / Enumerable
Classes/Modules

include Comparable def <=>(other) ...

Include Comparable and define <=> to get <, >, <=, >=, between? for free. Include Enumerable and define each to get map, select, etc.

open class / monkey patching
Classes/Modules

class String def shout upcase + "!!!" end end

Ruby classes are open — you can reopen any class (including built-ins) and add or override methods.

if / elsif / else / unless
Control Flow

if cond ... elsif cond ... else ... end

Standard conditionals. unless is the negated form of if. Both can be used as trailing modifiers.

case / when / in
Control Flow

case value when pattern then ... else ... end

Pattern matching with case. Ruby 3.x adds case/in for structural pattern matching.

Ternary / conditional assignment
Control Flow

cond ? true_val : false_val x ||= default x &&= transform

Ternary for inline conditionals. ||= assigns only if nil/false. &&= assigns only if truthy.

begin / rescue / ensure / raise
Control Flow

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

Exception handling. rescue catches errors, ensure always runs, raise throws exceptions.

Iterators (times / upto / downto)
Control Flow

5.times { |i| ... } 1.upto(10) { |n| ... } 10.downto(1) { |n| ... }

Numeric iterators — Ruby idiom instead of C-style for loops.

loop / while / until
Control Flow

while cond do ... end until cond do ... end loop do ... break if cond ... end

General-purpose loops. until is the negated while. loop runs forever until break.

File.read / File.write
File I/O

content = File.read("path") File.write("path", data)

One-shot read/write for entire files. Simple and commonly used for small files.

File.open with block
File I/O

File.open("path", "mode") do |f| ... end

Block form auto-closes the file handle. Modes: r (read), w (write), a (append), r+ (read-write).

Dir / File class methods
File I/O

Dir.glob("**/*.rb") File.exist?("path") File.basename / File.extname

Directory listing, file existence checks, and path manipulation utilities.

CSV / JSON stdlib
File I/O

require "csv" require "json"

Standard library modules for parsing and generating CSV and JSON data.

gem install / Gemfile
Gems/Bundler

gem install <name> # Gemfile: gem "rails", "~> 7.0"

RubyGems is the package manager. Gemfile declares dependencies, Bundler resolves and locks versions.

bundle install / exec / update
Gems/Bundler

bundle install bundle exec <command> bundle update <gem>

Install dependencies from Gemfile.lock, execute commands in the bundle context, or update specific gems.

Version constraints
Gems/Bundler

"~> 2.1" # pessimistic (>= 2.1, < 3.0) ">= 1.0, < 2.0"

Pessimistic constraint (~>) allows patch/minor updates but not major. Combine operators for precise ranges.

require / require_relative
Gems/Bundler

require "gem_name" require_relative "./local_file"

require loads gems and stdlib modules from $LOAD_PATH. require_relative loads files relative to the current file.