Ruby Reference
v1.0.0Quick-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
x = 42 y = 3.14
Numeric types — Ruby auto-promotes Integer to Bignum for large values. Underscores allowed for readability.
s = "hello" s = 'hello'
Double-quoted strings support interpolation and escape sequences. Single-quoted strings are literal.
:name / :"with spaces"
Immutable, interned identifiers — commonly used as hash keys and method names. Faster comparison than strings.
arr = [1, 2, 3] arr = Array.new(5, 0)
Ordered, indexed collection that can hold mixed types.
h = { key: "value" } h = Hash.new(0)
Key-value collection — symbol keys use shorthand syntax, string keys use hash rockets.
(1..10) # inclusive (1...10) # exclusive
Represents a sequence between two endpoints — used for iteration, slicing, and case matching.
nil true / false
nil is the absence of a value. Only nil and false are falsy — everything else is truthy (including 0).
"Hello, #{expr}" str1 + str2 / str1 << str2
Embed expressions in double-quoted strings. Concatenate with + (new string) or << (mutate in place).
str.gsub(pattern, replacement) str.sub(pattern, replacement)
gsub replaces all occurrences, sub replaces only the first. Accepts strings or regex.
str.split(delimiter) arr.join(delimiter)
split breaks a string into an array. join combines array elements into a string.
str.strip / str.chomp / str.chop
strip removes leading/trailing whitespace. chomp removes trailing newline. chop removes last character.
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.
str.freeze str.frozen?
freeze makes a string immutable. frozen? checks immutability. Frozen string literals can be enabled globally.
arr.map { |x| expr } arr.collect { |x| expr }
Transform each element, returning a new array. map and collect are aliases.
arr.select { |x| condition } arr.reject { |x| condition }
select keeps elements matching the condition. reject removes them. filter is an alias for select.
arr.reduce(init) { |acc, x| expr } arr.inject(:+)
Accumulate values into a single result. reduce and inject are aliases.
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.
arr.flat_map { |x| expr } arr.flatten(depth)
flat_map maps then flattens one level. flatten recursively flattens nested arrays.
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.
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.
h1.merge(h2) { |k, v1, v2| ... } h.transform_values { |v| expr }
merge combines hashes (block resolves conflicts). transform_values maps over values in place.
[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.
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.
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.
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(:name) [1,2,3].map(&method(:puts))
Convert a method reference into a callable object. & converts Proc/method to a block.
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 Name def initialize(args) @field = value end end
Classes use initialize as the constructor. Instance variables start with @.
attr_accessor :name, :age attr_reader :id attr_writer :password
Auto-generate getter and/or setter methods for instance variables.
class Child < Parent def method super end end
Single inheritance with < operator. super calls the parent method.
module Name def method; end end class Foo include Name end
Modules provide mixins (include for instance methods, extend for class methods) and namespacing.
include Comparable def <=>(other) ...
Include Comparable and define <=> to get <, >, <=, >=, between? for free. Include Enumerable and define each to get map, select, etc.
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 cond ... elsif cond ... else ... end
Standard conditionals. unless is the negated form of if. Both can be used as trailing modifiers.
case value when pattern then ... else ... end
Pattern matching with case. Ruby 3.x adds case/in for structural pattern matching.
cond ? true_val : false_val x ||= default x &&= transform
Ternary for inline conditionals. ||= assigns only if nil/false. &&= assigns only if truthy.
begin ... rescue ErrorType => e ... ensure ... end
Exception handling. rescue catches errors, ensure always runs, raise throws exceptions.
5.times { |i| ... } 1.upto(10) { |n| ... } 10.downto(1) { |n| ... }
Numeric iterators — Ruby idiom instead of C-style for loops.
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.
content = File.read("path") File.write("path", data)
One-shot read/write for entire files. Simple and commonly used for small files.
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.glob("**/*.rb") File.exist?("path") File.basename / File.extname
Directory listing, file existence checks, and path manipulation utilities.
require "csv" require "json"
Standard library modules for parsing and generating CSV and JSON data.
gem install <name> # Gemfile: gem "rails", "~> 7.0"
RubyGems is the package manager. Gemfile declares dependencies, Bundler resolves and locks versions.
bundle install bundle exec <command> bundle update <gem>
Install dependencies from Gemfile.lock, execute commands in the bundle context, or update specific gems.
"~> 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 "gem_name" require_relative "./local_file"
require loads gems and stdlib modules from $LOAD_PATH. require_relative loads files relative to the current file.