简体   繁体   中英

Ruby: gsub Replace String with File

So i'm working on a function that combines different configuration files I'm looping trough a configuration file and when I see a specific word (In this example "Test" I want this to be replaced with a File (Multiple Lines of text)

I have this for now

def self.configIncludes(config)
config = @configpath #path to config

combinedconfig = @configpath #for test purposes

doc = File.open(config)
text = doc.read
combinedConfig = text.gsub("test" , combinedconfig)
puts combinedConfig

So now I just replace my string "test" with combinedconfig but the output of this is my directory of where the config is placed

How do I replace it with text ? All help is appreciated!

If the files are not large you could do the following.

Code

def replace_text(file_in, file_out, word_to_filename)
  File.write(file_out,
   File.read(file_in).gsub(Regexp.union(word_to_filename.keys)) { |word|
     File.read(word_to_filename[word]) })
end

word_to_filename is a hash such that the key word is a to be replaced by the contents of the file named word_to_filename[word] .

If the files are large, do this line-by-line, perhaps using IO#foreach .

Example

file_in  = "input_file"
file_out = "output_file"
File.write(file_in, "Days of wine\n and roses")
  #=> 23
File.write("wine_replacement", "only darkness")
  #=> 13
File.write("roses_replacement", "no light")
  #=> 8
word_to_filename = { "wine"=>"wine_replacement", "roses"=>"roses_replacement" }

replace_text(file_in, file_out, word_to_filename)
  #=> 35
puts File.read(file_out)

Days of only darkness
 and no light

Explanation

For file_in , file_out and word_to_filename I used in the above example, the steps are as follows.

str0 = File.read(file_in)
  #=> "Days of wine\n and roses" 
r    = Regexp.union(word_to_filename.keys)
  #=> /wine|roses/

Let's first see which words match the regex:

str0.scan(r)
  #=> ["wine", "roses"]

Continuing,

str1 = str0.gsub(r) { |word| File.read(word_to_filename[word]) }
  #=> "Days of only darkness\n and no light" 
File.write(file_out, str1)
  #=> 35 

In computing str1 , the gsub first matches the the word "wine". That string is therefore passed to the block and assigned to the block variable:

word = "wine"

and the block calculation is performed:

str2 = word_to_filename[word]
  #=> word_to_filename["wine"]
  #=> "wine_replacement"
File.read("wine_replacement")
  #=> "only darkness"

so "wine" is replaced with "only darkness". The match on "roses" is processed similarly.

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