Ruby File Class (Reading/Writing/Appending)

Ruby’s built in File class provides powerful functionality that every Ruby/Rails programmer should master. Marcos Castiho has an excellent blog post on the Ruby File class. The file class is a subclass of the IO class and includes the Enumerable module so files have access to Ruby iterators that are familiar in other classes.

Use Unix commands to create a file named call_me on your Desktop. Add the lines “This is crazy” and “Well, not really” to the file.

$ touch ~/Desktop/call_me
$ echo "This is crazy" >> ~/Desktop/call_me 
$ echo "Well, not really" >> ~/Desktop/call_me 

Use irb to create an instance of the Ruby File class with the call_me file. Iterate over every line of the call me file and print each line to the console.

>> f = File.new("call_me")
>> f.each {|line| p line}
"This is crazy\n"
"Well, not really\n"

The file instance cannot be written to with File#new, but it can be closed.

>> f.close

The File#readlines method can conveniently be used to convert a file to an array of lines:

>> File.readlines("call_me") 
=> ["This is crazy\n", "Well, not really\n"]

When File objects are instantiated with a ‘w’ argument, the puts command can be used to write to the file. In the following example, we write “The art of getting robbed” to the call_me file, which will overwrite all of the existing lines in the file.

>> f = File.new("call_me", "w") 
>> f.puts("The art of getting robbed")
>> f.close

To append to an existing file, rather than wiping the file out completely, use the ‘a’ option when instantiating the File.

>> f = File.new("call_me", "a") 
>> f.puts("This will append an not wipe out the existing file")
>> f.close

Explicitly closing File objects is annoying and error prone so it is better to use the open method and read/write/append the file within a block. This one-liner will append the word “BLAH” to the file.

File.open("call_me", "a") { |f| f.puts("BLAH")  }

The post focused on reading, writing, and appending to files with the Ruby File class. The next post will discuss File#exists? and File#expand_path, two methods that are essential to understanding how a Rails application functions.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s