在Ruby中,您可以对从文件读取的数据执行字符串插值吗?

Tef*_*Ted 31 ruby string interpolation

在Ruby中,您可以引用字符串中的变量,并在运行时进行插值.

例如,如果声明一个变量fooequals "Ted"并声明一个"Hello, #{foo}"它插入的字符串"Hello, Ted".

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

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

interpolated_string = File.new('myfile.txt').read.interpolate
Run Code Online (Sandbox Code Playgroud)

但是最后interpolate一种方法不存在.

Dav*_*idG 29

我认为这可能是在Ruby 1.9.x中执行所需操作的最简单,最安全的方法(sprintf不支持1.8.x中的名称引用):使用"按名称引用"的Kernel.sprintf功能.例:

>> mystring = "There are %{thing1}s and %{thing2}s here."
 => "There are %{thing1}s and %{thing2}s here."

>> vars = {:thing1 => "trees", :thing2 => "houses"}
 => {:thing1=>"trees", :thing2=>"houses"}

>> mystring % vars
 => "There are trees and houses here." 
Run Code Online (Sandbox Code Playgroud)


Dan*_*aft 22

好吧,我是第二个stesch在这种情况下使用erb的答案.但你可以像这样使用eval.如果data.txt包含内容:

he #{foo} he
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样加载和插值:

str = File.read("data.txt")
foo = 3
result = eval("\"" + str + "\"")
Run Code Online (Sandbox Code Playgroud)

而且result将是:

"he 3 he"
Run Code Online (Sandbox Code Playgroud)

  • 至少做第一次转义`str`中的任何引号可能是个好主意,所以eval应该是:`eval('"'+ str.gsub(/"/,'\"')+'" ")` (2认同)

ste*_*sch 19

您可以使用而不是插值erb.这篇博客给出了ERB使用的简单示例,

require 'erb'
name = "Rasmus"
template_string = "My name is <%= name %>"
template = ERB.new template_string
puts template.result # prints "My name is Rasmus"
Run Code Online (Sandbox Code Playgroud)

Kernel#eval也可以用.但大多数时候你想要使用简单的模板系统erb.

  • 或者也许使用液体之类的东西会更安全。它与 erb 的概念相同,但恶意用户无法损坏您的应用程序。 (2认同)
  • 使用 eval 可能会带来巨大的安全风险,除非您信任文件内容,否则不建议使用。 (2认同)

小智 9

您可以使用IO.read(filename)将文件读入字符串,然后将结果用作格式字符串(http://www.ruby-doc.org/core-2.0/String.html#method-i- 25):

myfile.txt文件:

My name is %{firstname} %{lastname} and I am here to talk about %{subject} today.
Run Code Online (Sandbox Code Playgroud)

fill_in_name.rb:

sentence = IO.read('myfile.txt') % {
  :firstname => 'Joe',
  :lastname => 'Schmoe',
  :subject => 'file interpolation'
}
puts sentence
Run Code Online (Sandbox Code Playgroud)

在终端运行"ruby fill_in_name.rb"的结果:

My name is Joe Schmoe and I am here to talk about file interpolation today.
Run Code Online (Sandbox Code Playgroud)


And*_*imm 8

Ruby Facets提供了一个String#interpolate方法:

插.提供一种外部使用Ruby字符串插值机制的方法.

try = "hello"
str = "\#{try}!!!"
String.interpolate{ str }    #=> "hello!!!"
Run Code Online (Sandbox Code Playgroud)

注意:块必要,以便然后绑定调用者.

  • 你的链接已经死了.另外,在ruby 2.0.0中,我在类'String'上获得了方法'interpolate'的未定义方法. (2认同)

Pur*_*eas 6

已经给出了两个最明显的答案,但是如果由于某些原因他们不这样做,那就是格式运算符:

>> x = 1
=> 1
>> File.read('temp') % ["#{x}", 'saddle']
=> "The number of horses is 1, where each horse has a saddle\n"
Run Code Online (Sandbox Code Playgroud)

而不是#{}魔法你有更老的(但经过时间考验)%s魔法...