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
typescript
import { Injectable, PipeTransform, ArgumentMetadata,
A custom validation pipe in NestJS
validation
dto
recursion
Intermediate
10 steps
ruby
module CreditCard module_function def valid?(number)
Validating credit card numbers with Luhn
checksum
luhn-algorithm
validation
Intermediate
6 steps
ruby
class UserColor GOLDEN_RATIO_CONJUGATE = 0.618033988749895 def initialize(username)
Deriving a stable color from a username
hashing
color-theory
deterministic-mapping
Intermediate
7 steps
ruby
namespace :counter_cache do desc "Recalculate comments_count for posts after a backfill" task warm_post_comments: :environment do scope = Post.where(comments_count: nil).or(Post.where("comments_count < 0"))
Backfilling counter caches in a Rake task in Rails
counter-cache
batching
rake-tasks
Intermediate
6 steps
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 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.