想象一下,我有两个文件:
A.txt
This is a sentence with a #{variable}.
和红宝石脚本。
Iamascript.rb
...
variable = "period"
...
有什么方法可以读取.txt文件的内容并在放入之前插入变量吗? 这意味着运行rb-script时的输出应为
This is a sentence with a period.
.txt文件是动态的。
答案 0 :(得分:3)
您正在寻找的内容通常称为模板,您基本上已经定义了模板语言。 Ruby实际上在标准库中附带了一个名为 ERb 的模板语言,因此,如果您愿意稍微更改模板语言的语法,您可以使用它而不必创建自己的模板语言:
<强> A.TXT 强>:
This is a sentence with a <%=variable%>.
<强> Iamascript.rb 强>
require 'erb'
variable = 'period'
puts ERB.new(File.read('A.txt')).result(binding)
# This is a sentence with a period.
答案 1 :(得分:1)
有一个“显而易见”(但很糟糕)的解决方案,那就是评估。 eval
运行你给它的一些代码。
这是一个安全问题,但如果您需要#{...}
中需要复杂的表达式,可以将其找到。
如果您只关心安全性,那么更正确的方法是使用Ruby的格式化运算符:%
(类似于Python)。
template = "the variable's value is %{var}"
puts template % {var: "some value"} => prints "the variable's value is some value"
答案 2 :(得分:0)
假设文件"A.txt"
包含单行文本(或从文件中提取此行):
s1 = 'This is a sentence with a #{my_var}'
,第二个文件"Iamascript.rb"
包含:
s2 =<<_
line of code
line of code
my_var = "period"
line of code
line of code
_
#=> "line of code\n line of code\n my_var = 'period'\n line of code\nline of code\n"
让我们创建这些文件:
File.write("A.txt", s1)
#=> 35
File.write("Iamascript.rb", s2)
#=> 78
现在阅读"A.txt"
的第一行并提取以"\#{"
开头并结束"}"
的字符串,然后从该字符串中提取变量名称。
r1 = /
\#\{ # match characters
[_a-z]+ # match > 0 understores or lower case letters
\} # match character
/x # free-spacing regex definition mode
s1 = File.read("A.txt")
#=> "This is a sentence with a #{my_var}"
match = s1[r1]
#=> "\#{my_var}"
var_name = match[2..-2]
#=> "my_var"
现在阅读&#34; Iamascript.rb&#34;并查找与以下正则表达式匹配的行。
r2 = /
\A # match beginning of string
#{var_name} # value of var_name
\s*=\s* # match '=' and surrounding whitespace
([\"']) # match a single or double quote in capture group 1
([^\"']+) # match other than single or double quote in capture group 2
([\"']) # match a single or double quote in capture group 3
\z # match end of string
/x # free-spacing regex definition mode
#=> /
# \A # match beginning of string
# my_var # value of var_name
# \s*=\s* # match '=' and surrounding whitespace
# ([\"']) # match a single or double quote in capture group 1
# ([^\"']+) # match other than single or double quote in capture group 2
# ([\"']) # match a single or double quote in capture group 3
# \z # match end of string
# /x
如果找到匹配,则返回"A.txt"
中带有文字替换的行,否则返回nil
。
if File.foreach("Iamascript.rb").find { |line| line.strip =~ r2 && $1==$3 }
str.sub(match, $2)
else
nil
end
#=> "This is a sentence with a period"