Rails Insights

Working with Files in Ruby

Introduction

When working with Ruby, you may often need to read from or write to files. In this article, we will explore how to work with files in Ruby, including reading, writing, and manipulating file contents.

Reading from a File

To read from a file in Ruby, you can use the File class and its methods. The most common method for reading from a file is File.open, which opens a file and returns a file object. You can then use methods like read or each_line to read the contents of the file.

File.open('example.txt', 'r') do |file|
  file.each_line do |line|
    puts line
  end
end

Writing to a File

Writing to a file in Ruby is similar to reading from a file. You can use the File.open method with the 'w' mode to open a file for writing. You can then use methods like puts or write to write content to the file.

File.open('output.txt', 'w') do |file|
  file.puts 'Hello, world!'
end

Appending to a File

If you want to add content to an existing file without overwriting its contents, you can use the 'a' mode with File.open. This will open the file in append mode, allowing you to add content to the end of the file.

File.open('output.txt', 'a') do |file|
  file.puts 'This is a new line.'
end

Manipulating File Contents

Aside from reading and writing to files, Ruby also provides methods for manipulating file contents. For example, you can use the File.readlines method to read all lines of a file into an array, or the File.write method to write content to a file in one go.

lines = File.readlines('example.txt')
puts lines

File.write('output.txt', 'New content')

Conclusion

Working with files in Ruby is a common task that can be easily accomplished using the File class and its methods. Whether you need to read from, write to, or manipulate file contents, Ruby provides the tools you need to get the job done efficiently.

Published: June 23, 2024

© 2024 RailsInsights. All rights reserved.