【发布时间】:2013-06-29 15:47:31
【问题描述】:
我有一个来自外部库的字符串,如下所示:
s = " things.each do |thing|\n thing += 5\n thing.save\n end\n\n"
这个输入字符串不会改变。我需要使用 ERB 将其插入到文件中。例如:
erb = ERB.new("<%= s %>")
File.write("test.txt", erb.result(instance_eval('binding'))
我的问题是缩进。不对字符串做任何修改,文件会这样写:
things.each do |thing|
thing += 5
thing.run
end
注意缩进。然而,我想要做的是将文本均匀地插入另外两个空格,如下所示:
things.each do |thing|
thing += 5
thing.run
end
如果我这样做:
erb = ERB.new(" <%= s %>")
那么只有第一行会缩进。
things.each do |thing|
thing += 5
thing.run
end
我可以通过修改初始字符串来实现..
erb = ERB.new("<%= s.gsub(/ (\w)/, " \\1") %>")
.. 但这感觉有点乱。我真的不想在视图中这样做。有没有办法在 ERB 中缩进整个字符串,还是我不走运?我想我可能会。
【问题讨论】:
-
你试过了吗?
ERB.new("<%= ' ' + s %>")(这是一个 2 空格字符串被前置)。