Page 1 of 1

File Manipulation Basics

#1 nimajneb   User is offline

  • D.I.C Head
  • member icon

Reputation: 12
  • View blog
  • Posts: 116
  • Joined: 04-August 10

Posted 09 December 2010 - 11:42 AM

Ruby makes manipulating files very easy. Here is a quick run through on how to create, open, read, write, close, and delete files.

Creating Files

To create a new file, use the new method with the File class."foobar.txt", "w")

New accepts two arguements: the file name and the mode of the file. Acceptable modes to use in Ruby are:

r sets mode to Read only
r+ sets mode to Read/Write only
w sets mode to Write only
w+ sets mode to Write/Read only
a sets mode to Write only with pointer positioned at EoF
a+ sets mode to Read/Write only with pointer positioned at EoF

Opening Files

To open a file you have already created, use the open method with the File class

myfile ="foobar.txt")

You can use the above line of code with the methods listed above as well:

myfile ="foobar.txt", "w+")

Adding the w+ at the end will open this file in Read/Write Only.

Writing and Reading to Files

Make sure you have the file you wish to edit opened. You can check this with the closed? method:


This should return false if the file has been opened.

To write a line to your file, use the puts method with the File class:

myfile.puts("This is the first line in my new file")

Running this code again will add the next bit of text to a new line.

myfile.puts("This is the second line in my new file")

To read the file, you need to move the pointer back to the beginning of the file. To do this, use rewind:


Now that we are at the top of the file, we can read individual lines with:


or print the whole document to screen using the each method:

myfile.each (|line| print line)

Closing, Renaming, and Deleting Files

Once your done manipulating the file, you may want to close it.


Renaming the file is just as easy:

File.rename("foobar.txt", "newname.txt")

And when you're tired of the file all together, just delete it with:


Is This A Good Question/Topic? 0
  • +

Replies To: File Manipulation Basics

#2 MitkOK   User is offline

  • D.I.C Regular
  • member icon

Reputation: 32
  • View blog
  • Posts: 403
  • Joined: 09-August 07

Posted 25 December 2010 - 01:42 AM

You should mention that it's better to use open files using the block version to ensure closing it automatically:"myfile.txt", "r") do |file|
  # do stuff

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1