Phero Phero - 3 months ago 8
Ruby Question

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

Imagine I have 2 files:

A.txt

This is a sentence with a #{variable}.


and a ruby script.

Iamascript.rb

...
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.

Answer

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:

A.txt:

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

Iamascript.rb

require 'erb'

variable = 'period'

puts ERB.new(File.read('A.txt')).result(binding)
# This is a sentence with a period.