简体   繁体   English

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

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

I'm trying to read from a file a string that interpolates variables which are defined in the code, and substitutes the string value of those variables. 我正在尝试从文件中读取一个字符串,该字符串将插值代码中定义的变量,并替换这些变量的字符串值。

The text file: 文本文件:

my name is #{name}

the code: 编码:

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

Desired output: 所需的输出:

My name is CDJ

Actual output: 实际输出:

My name is #{name}

When output is line.inspect: 当输出为line.inspect时:

"My name is \#{name}"

Can anyone help me format this string correctly so it reads #{name} as a variable instead of a string with the inserted escape character? 谁能帮助我正确设置此字符串的格式,以便它将#{name}读取为变量,而不是带有插入的转义字符的字符串?

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

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

Consider this: 考虑一下:

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

Notes : 注意事项

  1. Variables can be provided through the hash. 可以通过散列提供变量。
  2. File can be switched with DATA to read contents from bottom of file after __END__ __END__之后,可以使用DATA切换File以从文件底部读取内容

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

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