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
ruby
class ConfigFlattener def initialize(config) @config = config end
Flattening nested config into dotted keys
recursion
hashes
tree-traversal
Intermediate
8 steps
go
package server import ( "context"
Composing HTTP middleware in Go
middleware
http-handlers
closures
Intermediate
8 steps
php
<?php namespace App\Http\Controllers;
Building a filtered product index in Laravel
query-builder
validation
conditional-queries
Intermediate
9 steps
ruby
class MetricSeries def initialize(readings, window: 5) @readings = readings @window = window
Rolling averages with each_cons in Ruby
sliding-window
enumerable
data-smoothing
Intermediate
7 steps
ruby
class Api::V1::ArticlesController < Api::V1::BaseController def index articles = Article .published
Building a JSON:API endpoint in Rails
serialization
eager-loading
pagination
Intermediate
7 steps
php
<?php namespace App\Support;
Retry with exponential backoff in PHP
retry
exponential-backoff
error-handling
Intermediate
7 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.