ruby
21 lines · 5 steps
Building a tree from flat rows in Ruby
Group flat rows by parent id once, then recurse to assemble a nested tree in a single pass.
Explained by
highlit
1def build_tree(rows, root_id: nil)
2 children_by_parent = Hash.new { |hash, key| hash[key] = [] }
3
4 rows.each do |row|
5 children_by_parent[row[:parent_id]] << row
6 end
7
8 attach = lambda do |parent_id|
9 children_by_parent[parent_id]
10 .sort_by { |row| [row[:position] || 0, row[:id]] }
11 .map do |row|
12 {
13 id: row[:id],
14 name: row[:name],
15 children: attach.call(row[:id])
16 }
17 end
18 end
19
20 attach.call(root_id)
21end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Bucketing rows by parent id up front turns tree-building into O(n) instead of repeated scans.
- 2A default block on Hash lets you append to keys without pre-initializing every bucket.
- 3A named lambda can call itself recursively because it closes over its own local variable.
Related explainers
typescript
import { Injectable, PipeTransform, ArgumentMetadata,
A custom validation pipe in NestJS
validation
dto
recursion
Intermediate
10 steps
ruby
module CreditCard module_function def valid?(number)
Validating credit card numbers with Luhn
checksum
luhn-algorithm
validation
Intermediate
6 steps
php
<?php final class MarkdownParser {
Building a small Markdown-to-HTML parser in PHP
state-machine
parsing
closures
Intermediate
10 steps
ruby
class UserColor GOLDEN_RATIO_CONJUGATE = 0.618033988749895 def initialize(username)
Deriving a stable color from a username
hashing
color-theory
deterministic-mapping
Intermediate
7 steps
javascript
function initScrollSpy() { const links = Array.from(document.querySelectorAll('.nav a[href^="#"]')); const sections = links .map((link) => document.querySelector(link.getAttribute('href')))
Building a scroll spy with IntersectionObserver
intersectionobserver
dom
event-driven
Intermediate
7 steps
python
from typing import Callable, Dict, Type class PluginRegistry:
A decorator-based plugin registry in Python
decorators
registry pattern
factory
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-tree-from-flat-rows-in-ruby-explained-ruby-999a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.