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
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 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.