在Ruby中,您可以在字符串中引用变量,并在运行时对它们进行插值。

例如,如果您声明一个变量foo等于"Ted",并且声明一个字符串"Hello, #{foo}",则它将插值到"Hello, Ted"

我无法弄清楚如何对从文件读取的数据执行魔术"#{}"插值。

在伪代码中,它可能看起来像这样:

interpolated_string = File.new('myfile.txt').read.interpolate

但是最后一个interpolate方法不存在。

最佳答案

可以使用 erb 代替插值。 This blog给出了ERB使用的简单示例,

require 'erb'
name = "Rasmus"
template_string = "My name is <%= name %>"
template = ERB.new template_string
puts template.result # prints "My name is Rasmus"

Kernel#eval 也可以使用。但是大多数时候,您想使用一个简单的模板系统,例如erb

关于ruby - 在Ruby中,您可以对从文件读取的数据执行字符串插值吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/346380/

10-11 00:52