Ruby - Writing Files


The IO and File classes represents objects that can be treated like any other objects we've worked with thus far. We send messages to the objects, they execute some method and return the result. Writing to a file is as simple as calling the write method:

>> File.open('file.txt', 'a+') do |file|
file.write('Hello, World!')
end

This code block opens the 'file.txt' file for writing (note the 'a+' mode). The string "Hello, World!" will be appended to the end of the file. The end of the block ensures that the file closes once the block is exited. We can accomplish the same feat with the append operator as we have seen many times before:

>> File.open('file.txt', 'a+') do |file|
file << 'Hello, World!'
end

The append operator can be a useful shortcut if you are writing multiple lines to a file. Keep in mind that you'll need to explicitly tell ruby when to start a new line. This is accomplished with the \n (newline) character.

>> File.open('file.txt', 'a+') do |file|
file << 'Hello, World!\n'
file << 'I am writing on line two\n'
file << 'I am writing on line three\n'
file << '\t Line four starts indented! what!?'
end

There are some other methods worth mentioning. Modifying a file may include actions other than writing text. For such actions as those Ruby's File class provides the methods:

  • delete
  • rename
  • chown
  • chmod

The first method takes one parameter, the name of the file to be deleted. The second method takes two, the name of the file and its new name. The last two methods are native to linux and should be familiar to linux/mac os users. The chown method changes the ownership of the file. Three parameters should be passed in: the numeric owner and group IDs, followed by the file name. Finally, the chmod method changes the file permissions (readable, writable, etc.).

results matching ""

    No results matching ""