繁体   English   中英

从文件解析字符串时删除转义字符

[英]removing escape characters when parsing a string from file

我正在尝试从文件中读取一个字符串,该字符串将插值代码中定义的变量,并替换这些变量的字符串值。

文本文件:

my name is #{name}

编码:

file = File.open("tesst.txt", "r")
arr = []
name = "CDJ"
file.each_line.with_index { |line, index|
  puts line
}
file.close

所需的输出:

My name is CDJ

实际输出:

My name is #{name}

当输出为line.inspect时:

"My name is \#{name}"

谁能帮助我正确设置此字符串的格式,以便它将#{name}读取为变量,而不是带有插入的转义字符的字符串?

file= 'tesst.txt'
name = 'CDJ'

File.readlines(file).each do |line|
  eval("puts \"#{line}\"")
end

考虑一下:

class Template
  def initialize(source: DATA)
    @text = source.read.chomp.split("\n")
  end

  def render(locals: {})
    locals.each do |key, value|
      instance_variable_set("@#{key}", value)
      self.class.send(:attr_reader, key)
    end

    @text
      .map { |line| eval("\"#{line}\"") }
      .join("\n")
  end
end

puts Template
  .new(source: File.open('./tesst.txt', 'r'))
  .render(locals: {name: 'George', age: 29})

__END__
my name is #{name}
I am #{age} years old

注意事项

  1. 可以通过散列提供变量。
  2. __END__之后,可以使用DATA切换File以从文件底部读取内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM