In Ruby, file input/output (I/O) can be performed using the File class. The File class provides a number of methods for reading from and writing to files.
Here is an example of reading from a file:
file = File.open("example.txt", "r") contents = file.read puts contents file.close
This code opens the file "example.txt" in read mode, reads the entire contents of the file into the contents variable, prints the contents to the console, and then closes the file.
Here is an example of writing to a file:
file = File.open("example.txt", "w") file.write("Hello, world!") file.close
This code opens the file "example.txt" in write mode, writes the string "Hello, world!" to the file, and then closes the file.
.jpg)
begin file = File.open("example.txt", "r") contents = file.read puts contents rescue puts "Error: could not read file" ensure file.close if file end
This code attempts to open the file "example.txt" in read mode, reads its contents, and prints them to the console. If an exception occurs, the error message "Error: could not read file" is printed. The ensure block is used to close the file, regardless of whether an exception occurred or not.
It's important to always close files after working with them, to release any resources they are using and prevent data corruption. In the examples above, the close method is called on the file object to close the file. Alternatively, you can use a block to automatically close the file when it is no longer needed:
File.open("example.txt", "r") do |file| contents = file.read puts contents end
In this example, the File.open method is called with a block. The block is passed a file object, and any code inside the block can use the file object to read or write data. When the block is exited, the file is automatically closed.
Overall, file I/O in Ruby is a powerful tool for working with data stored in files, and by using exception handling and proper resource management, you can ensure that your code is robust and reliable.
0 Comments