From: James Edward Gray II Date: 2006-03-24T07:13:42+09:00 Subject: Re: variable substitution in strings read from a file On Mar 23, 2006, at 3:31 PM, Stephen Bannasch wrote: > I have a bunch of template documents which I need to manipulate in > very simple ways. I'd like to be able to insert Ruby variables into > the template. Here is a very short example: > > file fruit_template.txt: This is a fruit: #{fruit}. > > fruit = "apple" > f = IO.read("fruit_template.txt") > > Then somehow I'd like to end up with this string: > "This is a fruit: apple." The easy answer to your question is to use eval(): >> fruit = "apple" => "apple" >> f = 'This is a fruit: #{fruit}.' => "This is a fruit: \#{fruit}." >> eval %Q{"#{f}"} => "This is a fruit: apple." The right answer is to use a template library, like the standard ERB: >> f = "This is a fruit: <%= fruit %>." => "This is a fruit: <%= fruit %>." >> require "erb" => true >> ERB.new(f).result(binding) => "This is a fruit: apple." Hope that helps. James Edward Gray II