Ruby provides a simple and intuitive way to read and write files. You can use the built-in File class to create, open, read, write, and manipulate files.

        Here are some examples of reading and writing files in Ruby:

Reading a file

file = File.open("file.txt", "r")
contents = file.read
puts contents
file.close

        In this example, we open the file "file.txt" for reading using the File.open method. We then read the contents of the file into the contents variable using the read method. Finally, we close the file using the close method.

Writing to a file

file = File.open("file.txt", "w")
file.write("Hello, world!")
file.close

        In this example, we open the file "file.txt" for writing using the File.open method. We then write the string "Hello, world!" to the file using the write method. Finally, we close the file using the close method.

Appending to a file

file = File.open("file.txt", "a")
file.write("Hello again, world!")
file.close

        In this example, we open the file "file.txt" for appending using the File.open method with the "a" mode. We then append the string "Hello again, world!" to the end of the file using the write method. Finally, we close the file using the close method.

Reading a file line by line

File.foreach("file.txt") do |line|
  puts line
end

        In this example, we open the file "file.txt" and read it line by line using the foreach method. Each line is passed to the block and printed to the console.

king if a file exists

if File.exist?("file.txt")
  puts "File exists!"
else
  puts "File does not exist."
end

        In this example, we use the File.exist? method to check if the file "file.txt" exists. If the file exists, we print "File exists!" to the console. Otherwise, we print "File does not exist.".

        These are just a few examples of the many ways you can read and write files in Ruby using the File class. The File class also provides many other methods for manipulating files, such as renaming, deleting, and copying files. Click here to know Ruby File i/o, Exceptions handling