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
python
from flask import Blueprint, jsonify, request, abort from .models import Article, db from .schemas import article_schema, articles_schema
Building a REST articles API with Flask Blueprints
rest-api
blueprints
serialization
Intermediate
7 steps
ruby
def build_tree(rows, root_id: nil) children_by_parent = Hash.new { |hash, key| hash[key] = [] } rows.each do |row|
Building a tree from flat rows in Ruby
recursion
hash-grouping
tree-structure
Intermediate
5 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
ruby
class FundsTransfer class InsufficientFundsError < StandardError; end def initialize(source:, destination:, amount:)
Atomic money transfers with Rails transactions
service object
database transactions
row locking
Advanced
9 steps
ruby
class Money include Comparable CURRENCY_SYMBOLS = { usd: "$", eur: "€", gbp: "£" }.freeze
Building an immutable Money value object in Ruby
value-object
immutability
comparable
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/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.