Site menu:

About Me

My name is Joe.
I want to become an expert programmer, and I invite you to follow along with me as I learn to program with Ruby.

Recent Posts

Categories

Donate

If you enjoy the content on this site then please consider Donating. This site is run by a recent college grad who works fulltime for not a whole lot. It would be tremendously helpful if you could donate and help fund this website.

How to Read & Write Files using Ruby – A Simple Diff Script Example

Ever since I learned how easy it was to manipulate files with Ruby I have been using it like crazy. And why not, it makes it possible to manipulate existing data and to save computed data. I wanted to write about this and when I needed to be able to easily view the changes made to a set of text documents then I knew that Ruby would be perfect for this. Using the File class it is very easy to open, read, and write to files and I would be able to illustrate this all within a diff script example.

This is all very easy to do, here in english is how the script works:
First I set the inputs, and use a couple of variables to represent the actual name of the files. Then I make a few arrays, each of which will eventually get loaded with their particular set of strings. There is one for each input, and one for the diff.
I use the Time method in order to take the time, this is done in order to measure the length of time the program takes. I did this just for fun because I wondered how fast the actual diff computation was.

Then I use a block to read through each file and append it to an array, it looks like this:

publicFile = File.open(public_copy, "r")
publicFile.each {|line|
publicArray << line
}

This style is helpful for reading through files and closing them all within a single each block.
I use this method for both of the inputs, and it pours out their contents into 2 different arrays. Then I use an array operation (a minus sign – ) to subtract the older (smaller) array from the newer (bigger) array. This will result in the set of ‘only new’ content being loaded into the 3rd array.

The rest is all straight forward, I make some variables to represent the ‘counts’ of each of the arrays. I also take the new Time.now and subtract the difference from the earlier Time variable and get the ‘length of the process’ time which I was looking for. Then I have a simple report that runs and displays the numbers of lines of content in each file, and then an if statement to create a new Diff.txt file if there is a need to.

To create the diff.txt file I use the same loop used earlier except with different variables:

diffFile = File.new("diff.txt", "w")
diffArray.each do |i|
diffFile.puts(i)
end

After that I just do a bit more text display stating whether or not a file was created — and that’s it! There’s nothing to it! Who knew it was so easy to tinker with files using Ruby!

Here is the complete script: