File I/O
The ability to open, read, and write from the filesystem is an important part of any language. Thankfully, Ruby has quite an extensive and user-friendly file I/O
interface.
The IO
class is responsible for all input and output operations in Ruby. The File
class is a subclass of the IO
class:
File.superclass => IO
When we interact with the filesystem, we are generally always working with the File
class, although it is helpful to understand where it sits in the class hierarchy.
Let's take a look at some common file operations:
- Creating files
- Reading from files
- Writing to files
Creating Files
We can create new files by instantiating a File
object and passing the name of the file and the file mode to the initializer:
file = File.new("new.txt", "w") => #<File:new.txt> file.close
When we create or open files using the File.new
method, we also need to call close
afterward to tell Ruby to release the...