From: Morton Goldberg Date: 2006-12-25T20:00:18+09:00 Subject: Re: A problem about replacing a string in a template. On Dec 25, 2006, at 3:20 AM, Kuang Dong wrote: > File 1: test.tpl > > Hello,#{name}! > > File 2: test.rb > > name = "jack" > f = File.open("test.tpl") > puts f.read > puts "Hello,#{name}" > f.close > > And the result is: > Hello,#{name}! > Hello,jack! > > How to change the "#{name}" to "jack"? AFAIK, the Ruby #{...} substitution facility only works when a string literal is evaluated and converted into a String object. Therefore, to do what you want using #{...} substitution, you will need to build a double-quoted string from the template file contents and then evaluate that string. For example: File.open('/tmp/test.tpl', 'w') do |f| f.write 'Hello, #{name}!' end name = "Jack" File.open("/tmp/test.tpl") do |f| puts eval('"' + f.read + '"') end However, you might also consider a different approach. Define your own template format and use String#gsub or String#gsub! to do the replacement. File.open('/tmp/test.tpl', 'w') do |f| f.write 'Hello, #name#!' end File.open("/tmp/test.tpl") do |f| puts f.read.gsub('#name#', 'Jack') end In the above example, I could have used String#sub instead of gusb since there was only one substitution to be made. Regards, Morton