问题描述
在Ruby中,您可以在字符串中引用变量,并且在运行时对它们进行插值.
In Ruby you can reference variables inside strings and they are interpolated at runtime.
例如,如果声明一个变量foo
等于"Ted"
并声明一个字符串"Hello, #{foo}"
,则它将插值到"Hello, Ted"
.
For example if you declare a variable foo
equals "Ted"
and you declare a string "Hello, #{foo}"
it interpolates to "Hello, Ted"
.
我无法弄清楚如何对从文件读取的数据执行神奇的"#{}"
插值.
I've not been able to figure out how to perform the magic "#{}"
interpolation on data read from a file.
在伪代码中,它可能看起来像这样:
In pseudo code it might look something like this:
interpolated_string = File.new('myfile.txt').read.interpolate
但是最后一个interpolate
方法不存在.
But that last interpolate
method doesn't exist.
推荐答案
Instead of interpolating, you could use erb
. This blog gives simple example of ERB usage,
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
这样的简单模板系统.
Kernel#eval
could be used, too. But most of the time you want to use a simple template system like erb
.
这篇关于在Ruby中,您可以对从文件读取的数据执行字符串插值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!