template = ‘some text #{variable}’ # single quotes for reason
variable = ‘filled’
res = some_method(template)
Here, res should have value ‘some text filled’.
Is there an easy way doing this in ruby. Hard way is of course parsing
and inserting text with my own method.
I would consider using double quotes an “easy way”. Either way, some
piece of code needs to to the parsing. If you only ever want to fill
in a single value you could as well use (s)printf.
Btw, parsing can be as easy as
def replace(template, values)
template.gsub /(?<!\)#{([^}]*)}/ do
values[$1]
end
end
template = ‘foo \#{bar}-#{bingo}-#{bongo}’
x = replace template, “bar” => “1”, “bongo” => “2”
p template, x
#note the double quotes inside the single ones
template = ‘“some text #{variable}”’
variable = ‘filled’
res = eval template
A better way could be to use ERB (included in the standard library):
require ‘erb’
template = ERB.new “some text <%= variable %>”
variable = ‘filled’
res = template.result