Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
159: Implementing a Min-Heap in Ruby
You've likely dealt with sorting arrays, but there are times when you don't need a fully sorted list—you just need to be able to grab the smallest (or largest) item quickly and efficiently. That's where a Min-Heap comes in. It's the backbone of priority queues and algorithms like Dijkstra's. Let's get into how to actually build one in Ruby.
Why use an array instead of a tree of objects?
When people first think of a heap, they imagine a binary tree with nodes and pointers. While that works, it's overkill and slow in Ruby. Because a heap is a "complete" binary tree, we can map it perfectly onto a standard array. I always recommend this approach because it keeps the memory footprint low and the access speeds high.
Here is the mental model for the indexing: if an element is at index i, its left child is always at 2i + 1, its right child is at 2i + 2, and its parent is at (i - 1) / 2. It feels like magic the first time you see it, but it's just basic arithmetic that saves us from creating hundreds of Node objects.
How do I actually implement the "bubble up" and "bubble down" logic?
The core of a Min-Heap is maintaining the "heap property": every parent must be smaller than or equal to its children. When you add an element, you break that rule, so you have to "bubble it up" to its rightful place. When you remove the root, you move the last element to the top and "bubble it down."
Here is a clean implementation. I've used a private swap method to keep the logic readable, as Ruby's parallel assignment makes this incredibly concise.
class MinHeap
def initialize
@heap = []
end
def push(value)
@heap << value
bubble_up(@heap.size - 1)
end
def pop
return nil if @heap.empty?
# Swap the root with the last element, then remove the root
swap(0, @heap.size - 1)
min = @heap.pop
bubble_down(0)
min
end
def peek
@heap[0]
end
private
def bubble_up(index)
parent_idx = (index - 1) / 2
return if index <= 0 || @heap[parent_idx] <= @heap[index]
swap(index, parent_idx)
bubble_up(parent_idx)
end
def bubble_down(index)
left_child_idx = 2 * index + 1
right_child_idx = 2 * index + 2
smallest = index
if left_child_idx < @heap.size && @heap[left_child_idx] < @heap[smallest]
smallest = left_child_idx
end
if right_child_idx < @heap.size && @heap[right_child_idx] < @heap[smallest]
smallest = right_child_idx
end
if smallest != index
swap(index, smallest)
bubble_down(smallest)
end
end
def swap(i, j)
@heap[i], @heap[j] = @heap[j], @heap[i]
end
end
What happens if I want to store objects instead of just numbers?
In a real project, you're rarely storing raw integers. You're probably storing Task objects or NetworkPacket objects. To handle this, you can't just use the < operator unless your objects implement the Comparable module.
If you don't want to mess with the class definition of the objects you're storing, I suggest passing a block to the initialize method or defining a priority method on your objects. For example, if you're building a task scheduler, your Task object might have a priority attribute. You would then replace @heap[index] with @heap[index].priority inside the bubble_up and bubble_down methods.
Just a heads-up: if two items have the same priority, the heap doesn't guarantee "first-in, first-out" order. If you need that, you'll need to add a secondary timestamp or counter to your priority comparison.
📋 Practical Task
Build a Priority-Based Event Processor
Now it's your turn. Imagine you are building a system that processes system events. Some events are "Critical" (Priority 1), some are "Warning" (Priority 2), and some are "Info" (Priority 3). You need to ensure that Critical events are always processed before Warning events, regardless of the order they arrived in.
- Create an
Eventclass that has aname(string) and apriority(integer). - Modify the
MinHeapimplementation from the lesson so that it storesEventobjects but compares them based on theirpriorityattribute. - Implement a method
process_next_eventthat pops the highest priority event (the lowest number) from the heap and prints:"Processing [Event Name] with priority [Priority]". - Test your implementation by pushing 5 events in random order (e.g., an "Info" event, then a "Critical" event, then a "Warning" event) and popping them one by one to verify they come out in the correct priority order.
There are no comments for now.