Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - How to write a new file with output from script

Tags:

I have a simple script that does some search and replace. This is basically it:

File.open("us_cities.yml", "r+") do |file|   while line = file.gets   "do find a replace"   end   "Here I want to write to a new file" end 

As you can see I want to write a new file with the output. How can I do this?

like image 968
thenengah Avatar asked Mar 13 '10 05:03

thenengah


People also ask

Which method is used to create a new file in Ruby?

new Method. You can create a File object using File. new method for reading, writing, or both, according to the mode string.


2 Answers

Outputting to a new file can be done like this (don't forget the second parameter):

output = File.open( "outputfile.yml","w" ) output << "This is going to the output file" output.close 

So in your example, you could do this :

File.open("us_cities.yml", "r+") do |file|   while line = file.gets     "do find a replace"   end   output = File.open( "outputfile.yml", "w" )   output << "Here I am writing to a new file"   output.close       end 

If you want to append to the file, make sure you put the opening of the output file outside of the loop.

like image 149
JoMo Avatar answered Sep 21 '22 12:09

JoMo


First you have to create a new file such as newfile.txt

Then change the script to

File.open("us_cities.yml", "r+") do |file|   new_file = File.new("newfile.txt", "r+")   while line = file.gets   new_file.puts "do find a replace"   end end 

This will make a new file with the output

like image 33
thenengah Avatar answered Sep 18 '22 12:09

thenengah