ruby 30 lines · 6 steps

Interpolating templates with dotted keys in Ruby

A small class replaces {{a.b}} placeholders by walking nested hashes, with an optional strict mode for missing keys.

Explained by highlit
1class TemplateInterpolator
2 PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/
3 
4 def initialize(strict: false)
5 @strict = strict
6 end
7 
8 def render(template, context)
9 template.gsub(PLACEHOLDER) do
10 key = Regexp.last_match(1)
11 value = resolve(key, context)
12 
13 if value.nil?
14 raise KeyError, "missing value for {{#{key}}}" if @strict
15 ""
16 else
17 value.to_s
18 end
19 end
20 end
21 
22 private
23 
24 def resolve(key, context)
25 key.split(".").reduce(context) do |scope, segment|
26 break nil unless scope.respond_to?(:[])
27 scope[segment] || scope[segment.to_sym]
28 end
29 end
30end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A capture group inside a regex passed to `gsub` lets each match drive its own replacement logic.
  2. 2Folding over the segments of a dotted key turns nested lookups into a single traversal that bails out safely.
  3. 3A strict flag lets one method serve both lenient rendering and fail-fast validation.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Interpolating templates with dotted keys in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code