Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Reading a File in Ruby
2.1.
Methods for Reading a File in Ruby
2.1.1.
Using the ‘new’ Keyword
2.2.
Ruby
2.2.1.
Using Open and Read Keyword
2.3.
Ruby
2.3.1.
Using Read Keyword to Split Files
2.4.
Ruby
3.
Writing a File in Ruby
3.1.
Methods for Writing a File in Ruby
3.1.1.
Using the ‘new’ Keyword
3.2.
Ruby
3.2.1.
Using the Open in Append Mode
3.3.
Ruby
3.3.1.
Using the write Method Directly
3.4.
Ruby
4.
Frequently Asked Questions
4.1.
What is Ruby Module?
4.2.
What is Ruby Programming Language?
4.3.
What is Ruby Exception?
5.
Conclusion
Last Updated: Mar 27, 2024
Hard

Read and Write Files in Ruby

Introduction

Ruby delivers us with a variety of methods for dealing with files. In simple terms, file handling includes numerous steps, such as creating a new file, reading the contents of a file, adding some material to a file, appending content to a file, deleting a file, and more. You can use Ruby to access various types of files, interact with the data they contain, and then probably produce a new file with your answer.

Read and Write Files in Ruby

Today, you will learn how to read and write files in Ruby so that you may extract the contents, create new files, and get the information you require.

Reading a File in Ruby

In Ruby, we may read any file system by using the keyword new over the file path and the file name, such as File.new('test.txt',"r"). Here, "r" means that we are opening the file in read mode, which means that we are reading the file. In Ruby, there are many significant methods for dealing with file read operations, all of which are derived from the I/O classes. Some significant file reading operations include read (read the file), puts (read the variable and print the value assigned to that variable), and so on.

Methods for Reading a File in Ruby

There are numerous ways in Ruby to read any file system utilizing the various techniques available in Ruby. Let's look at some examples of the methods.

Using the ‘new’ Keyword

  • First, a text file is created, and some content is inserted into it
     
  • We used a new keyword with two arguments, the first being the name and path of the file to be read and the second being the mode in which we are opening the file (in this example, we are opening the file in the read(r) mode)
     
  • The next part of the code is an if statement that checks if the file is empty to save unnecessary code flow for empty contents
     
  • Finally, using the sysread method, take 40 as the length of the words
     
  • It prints the first 40 characters from the file in the output
     

Code:

  • Ruby

Ruby

tempFile = File.new("test.txt", "r")
if tempFile
data = tempFile.sysread(40)
puts data
else
puts "File not found!"
end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Using the ‘new’ Keyword

Using Open and Read Keyword

  • First, the File.open method is used, which is a subclass that contains all file-related behavior
     
  • The open function takes a file path as an argument. Remember that the file name is passed directly here because the files test.txt and code1.rb are both in the same directory. If the file is at a different location, we can provide the entire path to it
     
  • After opening the file, use the read method on the output of the open result
     
  • Finally, we put the result of readData.read, which is the file's content
     

Code:

  • Ruby

Ruby

temporaryFile = File.open("test.txt")
file_data = temporaryFile.read
puts file_data
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Using Open and Read Keyword

Using Read Keyword to Split Files

  • First, File.read is written, which is a subclass that contains all file-related behavior
     
  • The split was then written as a chain form on the output of the command File.read as File.read.split
     
  • File.read will take the file path as input here. Remember that the file name is passed directly here because the files test.txt and file.rb are both in the same directory. If a file is in a different location, we can provide the entire path of the file
     
  • The split method divides the language into words and reads them line by line
     
  • You can see the output of the result, where each word is displayed as the sentence's output
     

Code:

  • Ruby

Ruby

readData = File.read("test.txt").split
puts readData
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Using Read Keyword to Split Files

Writing a File in Ruby

Ruby provides several methods and approaches to do a write operation on a file; all actions performed on any file system will be done with the Ruby File class. The file class system allows the developer to perform writing work on the file system by using various methods such as open, new, and write. It allows us to write either in append (add new contents on the existing content with newlines) mode or on normal write (, in Ruby, the shortest way to write the content will be done with the method), write (here write method will work in a variety of modes such as append and write).

Methods for Writing a File in Ruby

In Ruby, we have several techniques and methods for writing the contents of a file, such as new, open in append mode and write mode, and direct-write (write is also accessible in various modes such as append mode and write mode). Let us go over all of the different ways to write on any file.

Using the ‘new’ Keyword

  • First, a file is created called txt, and some content is inserted into it
     
  • We called a new function with two arguments, the first being the name and location of the file to be read and the second being the mode in which we are opening the file (in this example, we are opening the file in the write(+r) mode)
     
  • Use the if statement to check whether the file is empty or not
     
  • Finally, using the method syswrite, which will either write the content or just remove the existing contents and replace them with the contents supplied into the function. The overall length of the letter on the file will be returned by this function. The example shows that it yields 32
     
  • We can view the contents of the file test.txt both before and after the code block is executed
     

Code:

  • Ruby

Ruby

temporayFile = File.new("test.txt", "r+")
if temporayFile
data = temporayFile.syswrite("Welcome to Coding Ninjas Studio!")
puts data
else
puts "Not able to access the file"
end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Using the ‘new’ Keyword

Using the Open in Append Mode

Append mode means that each time we run the code, it will add new content to a new line. When we need older and new stuff on the file system, we do this process. The following example can be broken down into two steps.

  • In the first stage, we open the file test.txt and walk through each line, adding new text on each new line
     
  • In the second step, we open the file in read mode and print the entire contents
     

Code:

  • Ruby

Ruby

#Here, the argument "a" indicates we are opening the file in append mode.
File.open("test.txt","a") do |line|
line.puts "\r" + "Welcome again in file system"
end
File.open("test.txt").each do |line|
puts line
end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Using Open in Apprend Mode

Using the write Method Directly

In the below example, we are not opening the file. We are directly writing content on the file with the help of the method write. We are performing two main operations, which can be explained in two steps.

  • In the first stage, we write the content by supplying two arguments to the method write (file name and contents). We can additionally pass the writing mode, such as append or write (in the same way that the open method does)
     
  • Second, we read the file content that was added in the previous step
     

Code:

  • Ruby

Ruby

File.write('test.txt', 'This we are adding without opening the file')
File.open("test.txt").each do |line|
puts line
end
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

Using the Write Method Directly

Frequently Asked Questions

What is Ruby Module?

A Ruby module is a group of methods and constants. A module method can be either an instance method or a module method. They are comparable to classes in that they contain a set of methods, class definitions, constants, and other modules. They are defined in the same way as classes are.

What is Ruby Programming Language?

Ruby is an open-source, dynamic, reflective, general-purpose programming language with a focus on simplicity and productivity. Ruby combines Perl, Smalltalk, Eiffel, Ada, and Lisp capabilities. Ruby was created to be a new language that balances the features of Imperative languages.

What is Ruby Exception?

A Ruby exception is a class instance or descendant of the class Exception. When something goes wrong, the Ruby program exhibits abnormal behavior. By default, a Ruby program will terminate whenever an exception is thrown.

Conclusion

In this blog, we learned about reading and writing on the file system and saw several methods to read and write files in Ruby programming language. We learned how to use the methods through the usage of certain essential examples.

To better understand the topic, you can refer to What is RubyMethods in Ruby, and Ruby is an object-oriented language.

For more information, refer to our Guided Path on Coding Ninjas Studio to upskill yourself in PythonData Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more! 

Head over to our practice platform, CodeStudio, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!

Live masterclass