Read/Write files

This is a tutorial on how to open and write files with Ruby, of course there is always different ways to accomplish the same task within programming languages.

The objects e.g. File, have different functions associated with them. The File.new creates a new file, the IO (InputOutput) object is an allows for different Input output tasks, which in this case to read each line of the input file (countrys.txt) and assign the value to ‘line’. The puts prints out what has been read in, and the syswrite, which was created from the File.net outputs to the output file.

NOTE: the { } are the begin and end of a code structure, e.g. While begin; do something; end;

This is the code

OutFile = File.new("sqlrubycountry.txt","w");
 
IO.foreach("countrys.txt") { |line|
        puts line
        OutFile.syswrite("insert into country(place) values (\"#{line.strip}\");\n");
}
 
OutFile.close;

if you save that as rubyreadfile.rb and also create a countrys.txt file with what ever text you like, e.g.
United Kingdom
France
Germany
United States etc.

The output of the program (ruby rubyreadfile.rb) will display each line that is read from the input file and the output file will have some other text in it, for demonstrating purposes, have done some sql code.

Leave a Reply

Your email address will not be published. Required fields are marked *