Simple Dynamic Template

Sometimes we need to define a dynamic template before defining variables used in the template. Let me show a few examples how to solve this problem in Ruby.

The best way is to use the format string features from the Ruby:

string = "echo %{expr}" # -> "echo %{expr}"
string % {expr: 1}      # -> "echo 1"

simple-template-format.rb view raw

The first method is based on the ability to evaluate the Ruby expression in string:

string = 'echo #{expr}'  # -> "echo \#{expr}"
expr = 1                 # -> 1
eval("\"#{string}\"")    # -> "echo 1"

simple-template-eval.rb view raw