Morton Goldberg
12/25/2006 11:00:00 AM
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:
<code>
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
</code>
However, you might also consider a different approach. Define your
own template format and use String#gsub or String#gsub! to do the
replacement.
<code>
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
</code>
In the above example, I could have used String#sub instead of gusb
since there was only one substitution to be made.
Regards, Morton