Ruby IO: Using the Input/Output Functions of Ruby to Interface with the World

ruby ioThe Ruby programming language is cross-platform, interpreted and object-oriented. This language is used for developing Internet  applications. Its easy syntax enables a beginner to learn the programming language very quickly. The syntax is similar to that of C++ and Perl. It has a wide set of built-in functions which can be used directly in Ruby code. It incorporates support for several GUI like Tcl/Tk, GTK, and OpenGL. In this intermediate level tutorial, we walk you through the IO (Input/Output) part of the Ruby programming language. We assume that you are familiar with the basics of programming and object oriented concepts. Else we suggest that you first take this beginners course that helps you learn Ruby programming which is tailor made for those with no prior programming experience.

Introduction to Ruby

Ruby is a dynamic and object oriented programming language. Among other things, it has a dynamic type system and automatic memory management. This language is influenced by Perl, Smalltalk and Ada. It’s a server side scripting language which can be used to write common gateway interface scripts. It is scalable and its programs are easily maintainable. This introductory course gives a good overview of Ruby on Rails, and helps you understand how to use it. Alternatively you can read this awesome step-by-step guide on working with Ruby.

Ruby IO Concepts

All the IO methods of Ruby are derived from the class IO. The methods are read, write, gets, puts, readline, getc, and printf.   The directory path “#!/usr/local/bin/ruby”  should be declared in the beginning of every Ruby program. It gives the location of a ruby executable. The code is also known as the Shebang.

  • puts statement– The puts statement displays the value stored in the variable.
xyz = "Hello World"
puts xyz

The output will be the entire string “Hello World”

  • gets Statement – This is used to take input from the user from standard screen called STDIN. Here is an example
puts "Enter a value :"
xyz = gets
puts xyz
  • putc statement- compared to the puts statement, which displays the entire string on the screen, the putc statement outputs one character at a time.
xyz="Hello World!"
putc xyz

As the output only the first character of the string name; “H” will be displayed.

  • Print Statement- This is like the puts statement. The difference is that while the puts statement prints the contents and the cursor goes to next line. In the print statement the cursor is positioned on the same line.
print "Hello Mickey"
print "Good Morning"

The output of this program will be “Hello MickeyGood Morning”.

This course on Ruby shows you some good examples of using I/O and will help you use them more effectively.

File Manipulation Commands

  • The File.new Method- The File.new method cretaes a File object. In the end File.close method is used to close that file.
xyzFile = File.new("filename", "mode")
xyzFile.close
  • The File.open Method- This method creates a new file object and assigns that file object to a file. However while the File.open method can be associated with a block, the same cannot be object with the File.new method.
File.open("filename", "mode") dpo |xyzFile|

Below we have listed the different modes of opening a file.

File ModesDescription
rThis is the default mode. The file pointer is positioned at the start of the file. It is read only mode
r+It is read write mode. The file pointer is positioned at the start of the file
wIt is write only mode. If the file already exists, it is overwritten. If no file, creates a new file for writing.
w+It is read write mode. If the file already exists, it is overwritten. If no file, creates a new file for reading and writing.
aIt is write only mode. If the file already exists, the file pointer is positioned at the end of the file. The file opens in append mode. If no file, creates a new file for writing.
a+It is read write mode. If the file already exists, the file pointer is positioned at the end of the file.  The file opens in append mode. If no file, creates a new file for reading and writing.
  • The sysread Method – This method reads the contents of a file. Using this method the file can be open in any of the modes.

The following is the input text file. Which contains the following string  ”Ruby is an important programming language.”

Example: Program to read the content of a file:

xyzFile = File.new("ruby.txt", "r")
if xyzFile
   content = xyzFile.sysread(10)
   puts content
else
   puts "Not able to open file!"
end

The above program will output the first 10 characters of the file. The file pointer will now be positioned at the 11th character in the file.

  • The syswrite Method – This method writes the contents into a file. For achieving that, the file must be opened in write mode. Take a look at the example below

Example: Program to write a string into a file:

xyzFile = File.new(“ruby.txt”, “r+”)

if xyzFile
   xyzFile.syswrite("PERFECT")
else
   puts "Not able to open file!"
end

As a result of this program “PERFECT “will be written into the file.

  • The IO.readlines Method- This particular method returns the contents of a specified file line by line. Take a look at the following example

Example: Program to read file into an array:

 NewArray = IO.readlines("ruby.txt")
puts NewArray[0]
puts NewArray[1]

NewArray is an array variable. NewArray[0] will contain the first line of ruby.txt. NewArray[1] will contain the second line of the file.

  • The IO.foreach Method – This method is similar to read lines. It also returns line by line output. However it does not return an array and is associated with a block.
IO.foreach("ruby.txt"){|newblock| puts newblock}

This method will pass the contents of the file line by line to the variable new block. Finally the output will be displayed.

  • Renaming and Deleting Files-

It is possible to rename and delete files programmatically using the rename and delete methods. Here’s how  to rename an existing file ruby.txt:

File.rename( “ruby.txt”, “new.txt” )

And the code to delete an existing file new.txt would look like this:

 File.delete("new.txt")
  • File Modes and Ownership – The chmod method is used with a mask to change the mode or permissions/access list of a specified file.
file = File.new( "newprogram.txt", "w" )
file.chmod( 0700 )
  1. The below code tests whether a file exists before opening it:
File.open("newfile.rb") if File::exists?( "newfile.rb" )
  1. The below code finds whether the specified file is really a file
File.file?( "new.txt" )
  1. The below code finds out if the specified file name is a directory:
File::directory?( "/usr/local/bin" )

The above code returns true.

File::directory?( "file.rb" )

The above code returns false.

  1. The below code tests whether the file is readable, writable or executable:
File.readable?( "newfile.txt" )
File.writable?( "newfile.txt" )
File.executable?( "newfile.txt" )
  1. The below code finds out the size of a specified file.
File.size?( "newfile.txt" )
  1. The below code finds the type of a specified file.
File::ftype( "newfile.txt" )

We hope this tutorial gives you a good overview of how to use IO with Ruby. We at Udemy do have a bunch of courses, tailored exclusively for your special needs. For example if you’re a startup looking to get going with web development, you can check out this course specifically designed for you. Programming in Ruby is both fun and interesting. Go through the above examples, understand them and create your own unique code. This is the best way to master the art of programming in Ruby. Once you’re comfortable with them and ready to move on to the next level, you can take this Advanced course to Master Ruby Programming.