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 conditionals, and generate dynamic content. You'll learn pattern matching with regular expressions, recursive parsing, string interpolation, and data binding—essential skills for building web applications, code generators, and automation tools.

Difficulty: Intermediate

Instructions

  1. Read template from template.txt
  2. Read data from data.json (contains hash of variable values)
  3. Process template directives:
    • Variables: {{variable_name}} - replace with value from data
    • If statements: {{#if variable}}content{{/if}} - show content if variable is truthy
    • Loops: {{#each items}}{{this}}{{/each}} - repeat for each item in array
  4. Handle nested data: {{user.name}} accesses nested hash values
  5. Handle missing variables gracefully (replace with empty string)
  6. Write rendered output to output.txt
  7. Print confirmation: 'Template rendered successfully'
  8. Exit with status 1 if template syntax errors

Files

Editable
Read-only

Hints

Hint 1

Use String#gsub with regex and block to process patterns

Hint 2

Regex /pattern/m enables multiline matching

Hint 3

Capture groups: /{{(\w+)}}/ captures variable name in $1

Hint 4

Non-greedy match: .*? matches minimum characters

Hint 5

Check truthiness: value && value != false

Hint 6

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

Hint 7

Navigate hash: keys.each { |k| value = value[k] }

Hint 8

Replace {{this}} in loop: string.gsub('{{this}}', item)

Provided Files (Read-only)

1. Simple variable substitution

Input:
render_template('template.txt', 'data.json', 'output.txt')
Expected Output:
Template rendered successfully

2. Loop through array

Input:
render_template('template.txt', 'data.json', 'output.txt')
Expected Output:
Template rendered successfully

3. Conditional if statement

Input:
render_template('template.txt', 'data.json', 'output.txt')
Expected Output:
Template rendered successfully

4. Nested data access

Input:
render_template('template.txt', 'data.json', 'output.txt')
Expected Output:
Template rendered successfully
+ 3 hidden test cases