File Handling in Ruby - GeeksforGeeks

29 Nov, 2019
It is a way of processing a file such as creating a new file, reading content in a file, writing content to a file, appending content to a file, renaming the file and deleting the file.
Common modes for File Handling“r” : Read-only mode for a file.“r+” : Read-Write mode for a file.“w” : Write-only mode for a file.“w+” : Read-Write mode for a file.“a” : Write-only mode, if file exists it will append the data otherwise a new file will be created.“a+” : Read and Write mode, if file exists it will append the data otherwise a new file will be created.
Creating a new fileWe can create a new File using File.new() method for reading, writing or for both, according to the mode string. we can use fileobject.close() method to close that file.
Writing to the fileWith the help of syswrite method, you can write content into a file. File needs to be opened in write mode for this method.The new content will over write the old content in an already existing file.
Syntax
fileobject = File.new("filename.txt", "mode")
fileobject.syswrite("Text to write into the file")
fileobject.close()
Below is the implementation for creating a new file and writing into it.
# File Handling Program  # Creating a filefileobject = File.new("sample.txt", "w+");   # Writing to the filefileobject.syswrite("File Handling");       # Closing a filefileobject.close();                        
Output:
Description:A text file named sample.txt is created with read and write permission. The content “File Handling” is written to the file using syswrite method. Finally close the file. When you open the sample.txt file, it will contain the string “File Handling”.
Reading a fileThere are three different methods to read a file.
1. fileobject.sysread(20) – Return only the first 20 characters from that file2. fileobject.read – Return the entire content from a file3. fileobject.readlines – Return the values as an array of lines
sysread MethodThe sysread method is also used to read the content of a file. With the help of this method you can open a file in any mode. It will print till n characters mentioned in sysread method from the file.
Syntax
fileobject = File.new("filename.txt", "r")
fileobject.sysread(20)
fileobject.close()
Below is the implementation for reading the content from a file.
# File Handling Program  # Opening a filefileobject = File.open("sample.txt", "r");   # Reading the first n characters from a fileputs(fileobject.sysread(21));  # Closing a filefileobject.close();                           # Opening a filefileobject = File.open("sample.txt", "r");       # Read the values as an array of linesprint(fileobject.readlines);             puts  # Closing a filefileobject.close();                          # Opening a filefileobject = File.open("sample.txt", "r");   # Read the entire content from a fileprint(fileobject.read());      # Closing a filefileobject.close();                         
Output:
Description:The sample text file contains the string “File handling in Ruby language”. The file is opened with read-only permission. The above output shows the different way of reading the file and print it. The sysread method read only 21 characters and then print the first 21 characters. The readlines method read the values as an array of lines. The read method read the entire content as a string from the file.
Renaming and Deleting a fileRuby files are renamed using rename method and deleted using delete method.
File InquiriesTo check whether the file exists or not
# Rename the file nameputs File.rename("sample.txt", "newSample.txt")   # Delete the existing fileputs File.delete("sample1.txt")      # Checking the old filename is existing or not puts File.file?("sample.txt")  # Checking the renamed file is exiting or notputs File.file?("newSample.txt")  # Checking the file have read permissionputs File.readable?("newSample.txt")   # Checking the file have write permissionputs File.writable?("newSample.txt")        
Output:
Description:The rename method is used to rename the file contain the old name with the new name and the rename method print ‘0’ for the file is renamed, otherwise print ‘1’.The delete method is used to delete the exiting file and it will print ‘1’ if the file is deleted otherwise print ‘0. The file? method is used to check if the file is exists or not. It will return false if the file is not exists and otherwise true. In our case the sample.txt text file is not exists because we renamed it to newSample.txt file so it will return false. The newSample file is existing, so it will return true. The newSample file is having both read and write permission, so it will return true for last two statement.
Picked
Ruby-Basics
Ruby
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Data Types
Ruby | Numeric round() function
Ruby | String capitalize() Method