Ruby File Open: Opening a File in Ruby with Different Modes

Ruby File OpenRuby was designed by a Japanese programmer named Yukihiro “Matz” Matsumoto in the 90s.  Ruby, which is based on languages like Perl, Smalltalk, Ada, Lisp and Eiffel,  has steadily grown in popularity since then. It was designed to be simple to understand and implement, even for new programmers. Ruby has an automatic memory management system as well as a dynamic type system. The Ruby script was meant to let you do more with less, and there was an emphasis on building a language that supported multiple programming paradigms. It was also designed to run on all possible platforms- you can run it on Windows, Linux and Mac OS X.  If you are a programmer, or if you have studied a computer language in the past, it’ll be relatively easy for you to learn Ruby. If you’re looking to pick up the basics of Ruby to give yourself an advantage at work, or if you just want to learn it to bolster your resume, you are welcome to sign up for a beginners Ruby course with us. You will be able to write your own programs in the language in no time at all.

Ruby was designed to be a true object-oriented language. Several languages, like Python, came close, but they weren’t made to be scripting, object-oriented languages. Ruby has several features that make it a powerful and effective language- it runs on an object-oriented model, and it includes exception handling capabilities, iterators, mixins, closures, garbage collection capabilities and, of course, classes and inheritance.

Opening a File in Ruby

In this tutorial, we’ll tell you how to open an existing file in Ruby. This is the most basic operation required for any file manipulation. To open an existing file, you can use the File.open method. This method can also be used to create a file object and assign it to a file. This method is similar to the File.new method which is used to create a File object – the only difference between the two being that the File.open method can be associated with a block, unlike the File.new method. The syntax to open an existing file using Ruby is as follows:

file = File.open (“yourfilename.txt”)

To check whether a file is already open, you can use the following command:

file.closed?

If Ruby returns a false value, it means that the file is currently open. To see how this is used in real programming, check out this course on Ruby, that teaches Ruby from scratch. You can also read this step by step tutorial on how to work with Ruby.

Opening a File using Different Modes in Ruby

Ruby lets you open a file with different permissions (modes). You can open a file in a read only mode, write only mode, or a read-write mode, for example. The syntax to open a file in a mode is as follows:

file = File.open (“yourfilename.txt”, “mode”)

If you don’t specify any mode, it will default to a read-only mode. Lets take a look at the different modes available, with examples.

  • Read Only

Read only permission is denoted by ‘r’.  The read only mode is the default mode. The file pointer points to the beginning of the file, by default. If you open a file as read only, you cannot edit it or change it in any way.

file = File.open ('myfile.txt', 'r')

  • Write Only

Write only permission is denoted by ‘w’. This mode should be used when you only want to add data or rather write into a file. If you set a file to write only, you will not be able to read back from it. The file pointer starts at the beginning of the file. The file, if it exists, is overwritten. Otherwise, a new file is created.

file = File.open ('myfile.txt', 'w')
  • Append only

Append/Write only permission  is denoted by ‘a’. The main difference from the previous option is that the file pointer starts at the end of the file. This means the existing data in the file is not overwritten. We can only add on to it. If the file doesn’t exist, a new file is created.

file = File.open ('myfile.txt', 'a')
  • Read- write permission ‘r+’

Read- write permission is denoted by ‘r+’. You can both read and modify a file with this. The file pointer starts at the beginning of the file by default, enabling you to start reading from the very beginning.

file = File.open ('myfile.txt', 'r+')
  • Read-write permission ‘w+’

Like the previous mode, this one also opens a file with both read and write permissions. However, this command removes all existing data in the file, and effectively overwrites an existing file. If a file with the specified name does not exist, you a new file is created.

file = File.open ('myfile.txt', 'w+')
  •  Read and write permission ‘a+’

This is similar to the ‘w+’ mode, with the difference that the pointer is positioned at the end of the file. This means we append to the file and do not overwrite it. If the file exists, it can be appended. If it doesn’t exist, a new file is created.

file = File.open ('myfile.txt', 'a+')
  • Binary File mode ‘b’

This mode is used along with the permissions given above. It can only be run in DOS/Windows

file = File.open ('myfile.txt', 'b')

To see some real world program samples with these different modes, you can take this practical training course on Ruby.

Closing a File

A good programming practice is to always close a file once you are done using it. The command to close an open file is:

file.close

If you enter the command properly, you will get the result “nil”. To learn a few other basic file manipulation functions in Ruby, check out this course.

Example to Read from a File

# Open a file and read from it
File.open('test1.rb', 'r') do |f1| 
 while line = f1.gets 
 puts line 
 end 
end 
f1.close

In this example, we open a file test1.rb. In a loop, we then read from it, into line. We continue reading until there is no more data left in f1. Note that we remember to close the file. Of course, somewhere else in the program you should process or use the read data you’ve saved in line in some way!

Example to Write to a File

# Create a new file and write to it 
File.open('test2.rb', 'w') do |f2| 
 f2.puts "Created new file!" 
end
f2.close

This simple example shows you how to create a new file, and write a simple line of text into it.

You need to know how to open files and set permissions to use them effectively in your Ruby programs. You don’t want to inadvertently overwrite a file instead of appending to it, else you’ll loose your data. Opening a file with read permissions, and then wondering why you’re unable to write to it, can be a rather nasty problem to have to debug.

As usual, do remember that practice makes perfect. Make sure you experiment with these modes on your own. Feel free to refer back to this thorough Ruby course, if you need help at any time. And once you’re ready to move on to the next level, this Advanced Ruby course can help you attain mastery.