Cheat sheet for managing files from Ruby

Creating a New File New files are created in Ruby using the new method of the File class. The new method accepts two arguments, the first being the name of the file to be created and the second being the mode in which the file is to open. Like, file =“filename”, “mode”) Eg:

file ="file.txt", "w")
Supported modes are:
r Read only access.
r+ Read and write access.
w Write only access.
w+ Read and write access.
a Write only access.
a+ Read and write access.

Opening Existing Files

You can open the existing files using the open method. Eg:
file ="temp.txt")
If the file is already opened, we can close it by using the close method. Eg:

Reading and Writing Files

Once we’ve opened an existing file or created a new file we need to be able to read from and write to that file. We can read/write using different methods.

sysread Method:

You can use the method sysread to read the contents of a file. Eg:
file ="input.txt", "r")
if file
   content = file.sysread(10)
   puts content
  puts "cannot open the file"
This statement will output the first 10 characters of the file.

syswrite Method:

You can use the method syswrite to write the contents into a file. Eg:
file ="input.txt", "r+")
if file
   puts "Unable to open file!"
It writes ‘Hello’ into the file input.txt.

each_byte Method:

This method belongs to the class File. The method each_byte is always associated with a block. Eg:
file ="input.txt", "r+")
if file
   file.each_byte {|ch| putc ch }
   puts "Unable to open file!"
Characters are passed one by one to the variable ch and then displayed on the screen.

IO.readlines Method:

The class File is a subclass of the class IO. This method returns the contents of the file line by line. Eg:
arr = IO.readlines("input.txt")
puts arr[0]
puts arr[1]
Each line of the file input.txt will be an element in the array arr. Therefore, arr[0] will contain the first line, whereas arr[1] will contain the second line of the file.

IO.foreach Method:

This method also returns output line by line. The difference between the method foreach and the method readlines is that the method foreach is associated with a block. Eg:
IO.foreach("input.txt"){|block| puts block}
This code will pass the contents of the file test line by line to the variable block, and then the output will be displayed on the screen.

Renaming and Deleting Files

Files are renamed and deleted in Ruby using the rename and delete methods respectively. For example, we can create a new file, rename it and then delete it:"tempfile.txt", "w")
=> #<File:tempfile.txt>
File.rename("tempfile.txt", "newfile.txt")
=> 0
=> 1