Ruby Cheatsheet

Quick reference for Ruby basics — structures, functions, loops, and threading.

Data Structures

Structure Syntax Notes
Array [1, 2, 3] Ordered, indexed from 0
Hash {a: 1, b: 2} Key-value; symbols or string keys
Set Set[1, 2, 3] Unique values; require set
Range 1..10 / 1...10 Inclusive/exclusive endpoint
Queue Queue.new Thread-safe FIFO

Functions

# Method definition
def greet(name)
  "Hello, #{name}"
end

# Default parameters
def connect(host: "localhost", port: 3000)
  "#{host}:#{port}"
end

# Block / Proc / Lambda
square = -> (x) { x ** 2 }
square.call(4)  # => 16

# Splat operator
def sum(*nums)
  nums.sum
end

Loops & Iteration

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

# map / collect
doubled = [1, 2, 3].map { |n| n * 2 }

# select / reject
evens = (1..10).select(&:even?)

# times
5.times { |i| puts i }

# while / until
i = 0
while i < 5
  puts i
  i += 1
end

# for
for item in [1, 2, 3]
  puts item
end

Threading & Concurrency

# Threads
threads = 5.times.map do |i|
  Thread.new { puts "Thread #{i}" }
end
threads.each(&:join)

# Mutex
mutex = Mutex.new
counter = 0
threads = 10.times.map do
  Thread.new { mutex.synchronize { counter += 1 } }
end
threads.each(&:join)

# Queue (thread-safe)
queue = Queue.new
queue.push("job")
queue.pop  # blocks if empty

# Ractor (Ruby 3+)
ractor = Ractor.new { Ractor.receive }
ractor.send("hello")
ractor.take  # => "hello"