Ruby - Open and Read from a File

1. Introduction

Reading from files is a fundamental operation in programming, allowing data to be ingested, processed, and utilized. In Ruby, file reading is simplified due to its expressive syntax and powerful built-in classes. In this guide, we will explore how to open and read content from a file using Ruby.

2. Program Steps

1. Utilize the File class to open an existing file.

2. Read content from the file.

3. Close the file to ensure resources are released.

3. Code Program

# Open an existing file and read its content
File.open('sample.txt', 'r') do |file|
  # Read and print each line from the file
  file.each_line do |line|
    puts line
  end
end
# Print a message after reading from the file
puts "Content has been read from sample.txt."

Output:

Hello, World!
This is a sample text.
Content has been read from sample.txt.

Explanation:

1. The File.open method is utilized to open an existing file. The first argument represents the filename (sample.txt in this instance), while the second argument 'r' denotes the mode in which the file should be opened. Here, 'r' indicates "read mode," which allows data to be read from the file.

2. As with writing to a file, the do |file| ... end block ensures that the file gets closed once the operations inside the block are done. This approach is a best practice in Ruby to ensure efficient file closure and resource handling.

3. Within the block, file.each_line is used to iterate over each line of the file, and the puts method prints each line to the console.

4. Once the block is executed, the file gets closed, and a confirmation message is displayed to the console.

With the help of Ruby's File class, reading from files becomes an effortless task, allowing for seamless data ingestion and processing.


Comments