2015-12-09 74 views
0

我可以读取包含#{var_name}的文件吗?当我读取并打印它时,请写入var_name的值?在文本文件中读取带有变量的文件

我尝试使用

File.open(filename, "w").read 

把它作为一个字符串,但我没有找到解决办法:

var_name = "HelloWorld" 
f = File.open("file.ex", "r").read 
    # puts f.class => String 
puts f 
    # #{var_name} is print and no HelloWorld 
+4

对此,您可以使用[ERB](http://ruby-doc.org/stdlib-2.2.3/libdoc/erb/rdoc/ERB.html)。 –

回答

0

解决方案:

tamplate.erb文件里面的变量a <%= var_name %>

in script.rb

require 'erb' 
template = File.open("template.erb", "r") 
str_template = ERB.new(template.read).result() 
template.close 

file = File.new("newfile", "w") 
file.puts(str_template) 
file.close 

感谢Sergio Tulentsev!

相关问题