ruby
42 lines · 8 steps
Flattening nested config into dotted keys
A Ruby class that walks nested hashes and arrays into flat dotted-path keys, and rebuilds them again.
Explained by
highlit
1class ConfigFlattener
2 def initialize(config)
3 @config = config
4 end
5
6 def to_dotted
7 flatten(@config)
8 end
9
10 def self.expand(flat)
11 flat.each_with_object({}) do |(key, value), acc|
12 segments = key.to_s.split(".")
13 leaf = segments.pop
14 target = segments.reduce(acc) { |node, seg| node[seg] ||= {} }
15 target[leaf] = value
16 end
17 end
18
19 private
20
21 def flatten(node, prefix = nil)
22 node.each_with_object({}) do |(key, value), acc|
23 path = [prefix, key].compact.join(".")
24
25 case value
26 when Hash
27 acc.merge!(flatten(value, path))
28 when Array
29 value.each_with_index do |item, index|
30 indexed = "#{path}[#{index}]"
31 if item.is_a?(Hash)
32 acc.merge!(flatten(item, indexed))
33 else
34 acc[indexed] = item
35 end
36 end
37 else
38 acc[path] = value
39 end
40 end
41 end
42end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Recursion naturally mirrors nested data structures, threading a growing prefix down each level.
- 2Building an accumulator with each_with_object keeps transformations pure and side-effect free.
- 3A flatten/expand pair only round-trips cleanly if both sides agree on the exact key grammar.
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
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 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
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/flattening-nested-config-into-dotted-keys-explained-ruby-684f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.