Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby writing to a file in memory (not actually writing to it)

So I have this program that works with passing around a string (this string is the path of the file it is supposed to read)

Now I have a method that has to open that file. change the text with Gsub and than output that file again (The original file can't be edited) but I need to eventually output that changed file

this is the method i'm using to change my file (simplified)

def self.changeFile(myfile)
myfile = @path

doc = File.open(myfile)
text = doc.read

text.gsub!("change" , "changed")

return text

the problem with this is I get the entire file as string returned. My other methods work with the input of a "string" pathname

So my question is is there anyway I can write my text to the file I changed in the memory, so without actually changing the original file?

I was thinking about using "Tempfile" or "StringIO" but I don't know if this is the right thing to go about

All Help is appreciated

like image 434
FroggyFreshh Avatar asked Dec 19 '25 12:12

FroggyFreshh


1 Answers

You can use temple for this:

def self.changeFile(myfile)
  myfile = @path
  tempfile = Tempfile.new("changed")
  tempfile << File.open(myfile).read.gsub("change" , "changed")
  tempfile.close
  tempfile.path
end
like image 51
Maxim Pontyushenko Avatar answered Dec 21 '25 04:12

Maxim Pontyushenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!