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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Recursion naturally mirrors nested data structures, threading a growing prefix down each level.
  2. 2Building an accumulator with each_with_object keeps transformations pure and side-effect free.
  3. 3A flatten/expand pair only round-trips cleanly if both sides agree on the exact key grammar.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Flattening nested config into dotted keys — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code