Ruby Cheatsheet
DSA and Interview Idioms
Use this Ruby reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Frequency Maps
counts = Hash.new(0) "banana".each_char { |ch| counts[ch] += 1 } counts # {"b"=>1, "a"=>3, "n"=>2} words.tally # Ruby 2.7+: frequency hash
Use Hash.new(0) for counters. Use tally when you already have an array or enumerable.
Stack and Queue
stack = [] stack << 1 stack << 2 stack.pop # 2 queue = [] queue << "a" queue << "b" queue.shift # O(n), okay for tiny queues
For large queues, avoid repeated shift; keep a head index instead.
queue = [] head = 0 queue << start while head < queue.length node = queue[head] head += 1 visit(node) end
Two Pointers
def pair_sum?(nums, target) left = 0 right = nums.length - 1 while left < right sum = nums[left] + nums[right] return true if sum == target sum < target ? left += 1 : right -= 1 end false end
Two pointers usually assume sorted input or a monotonic condition.
Sliding Window
def max_window_sum(nums, k) return nil if nums.length < k window = nums.first(k).sum best = window k.upto(nums.length - 1) do |i| window += nums[i] - nums[i - k] best = [best, window].max end best end
Use a running total or count hash instead of recomputing the whole window.
Binary Search
def lower_bound(nums, target) left = 0 right = nums.length while left < right mid = (left + right) / 2 if nums[mid] < target left = mid + 1 else right = mid end end left end [1, 3, 5, 7].bsearch { |x| x >= 4 } # 5
Array#bsearch returns a matching value. Write index-based search when you need insertion positions.
Graph Adjacency Lists
graph = Hash.new { |h, k| h[k] = [] } edges.each do |a, b| graph[a] << b graph[b] << a end seen = Set.new stack = [start] until stack.empty? node = stack.pop next unless seen.add?(node) graph[node].each { |nxt| stack << nxt } end
Remember require "set" before using Set. The block hash default avoids shared mutable arrays.
Sorting with Blocks
people.sort_by { |p| [p[:score], p[:name]] }
people.sort { |a, b| b[:score] <=> a[:score] }sort_by is concise for derived keys. Use <=> when the comparison itself is custom.