2015-12-09 128 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!

相關問題