Ruby 读取文本文件中包含变量的文件
我是否可以读取包含Ruby 读取文本文件中包含变量的文件,ruby,Ruby,我是否可以读取包含{var\u name}的文件,并在读取和打印时写入var\u 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
{var\u name}
的文件,并在读取和打印时写入var\u 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
解决方案:
tamplate.erb
文件,其中包含变量
在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
感谢塞尔吉奥·图兰采夫 你可以用这个。