Phero Phero - 4 months ago 13
Ruby Question

Ruby Return the content of a text(.txt) file after replacing variables

Imagine I have 2 files:


This is a sentence with a #{variable}.

and a ruby script.


variable = "period"

Is there any way I can read the content of the .txt file and insert the variable before puts'ing it?
This means my output when running the rb-script shall be

This is a sentence with a period.

The .txt file is dynamic.


What you are looking for is commonly called templating, and you have basically defined a template language. Ruby actually ships with a template language called ERb in the standard library, so, if you are willing to change the syntax of your template language a bit, you can just use that instead of having to invent your own:


This is a sentence with a <%=variable%>.


require 'erb'

variable = 'period'

# This is a sentence with a period.