Challenge

Problem

Template engines power web frameworks, email systems, and code generators by dynamically inserting data into predefined structures. This drill teaches you to parse template syntax, substitute variables, handle loops, and generate dynamic content. You'll learn pattern matching with regular expressions, string manipulation, and data binding—essential skills for building web applications, code generators, and automation tools.

Difficulty: Intermediate

Instructions

  1. Read template string and data hash
  2. Process template directives:
    • Variables: {{variable_name}} - replace with value from data
    • Loops: {{#each items}}{{this}}{{/each}} - repeat for each item in array
  3. Handle nested data: {{user.name}} accesses nested hash values
  4. Handle missing variables gracefully (replace with empty string)
  5. Return the rendered output string

Files

Editable

Hints

Hint 1

Use String#gsub with regex and block to process patterns

Hint 2

Regex for variables: /{{([\w.]+)}}/

Hint 3

Regex for each loops: /{{#each (\w+)}}(.*?){{/each}}/m

Hint 4

The /m flag enables multiline matching

Hint 5

Capture groups are accessed with $1, $2, etc.

Hint 6

Non-greedy match: .*? matches minimum characters

Hint 7

Split nested path: 'user.name'.split('.') => ['user', 'name']

Ruby 3.4

1. Simple variable substitution

Input:
template = "Hello {{name}}!"
data = {'name' => 'Alice'}
puts render_template(template, data)
Expected Output:
Hello Alice!

2. Loop through array

Input:
template = "Items: {{#each items}}{{this}} {{/each}}"
data = {'items' => ['a', 'b', 'c']}
puts render_template(template, data)
Expected Output:
Items: a b c 

3. Nested data access

Input:
template = "User: {{user.name}}, Age: {{user.age}}"
data = {'user' => {'name' => 'Bob', 'age' => 30}}
puts render_template(template, data)
Expected Output:
User: Bob, Age: 30

4. Missing variable returns empty

Input:
template = "Hello {{name}}! Your score: {{score}}"
data = {'name' => 'Carol'}
puts render_template(template, data)
Expected Output:
Hello Carol! Your score: 
+ 2 hidden test cases