简体   繁体   中英

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:

"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?

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__

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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