Published Jul 29, 2021Updated Oct 19, 2021
Contribute to Docs
File class is used for working with file objects in Ruby.
Create a New File
To create a new
File object, use the
.new() method and pass in:
- A string
namefor the new file.
modeto indicate which operations can be done to the file.
Common modes include the following:
||Read: Start from the beginning of the file.|
||Read and write: Start from the beginning of the file.|
||Write: Start from the beginning of the file.|
||Rread and write: Overwrite the existing or create a new one.|
||Append (write-only): Start writing from the end of the existing file or create a new one.|
||Append (read and write): Start reading and/or writing from the end of the existing file or create a new one.|
File object can be assigned to its own variable, like in the example below:
example_file = File.new("exampleFile.txt", "w")puts example_file# Output: #<File:0x00007fab5113b790>
Open and Close a File
To open a file, use the
File.new("exampleFile.txt", "w")File.open("exampleFile.txt", "r")
To close the file, use the
.open() with a
do...end block, the file will
.close at the end.
File.open("exampleFile.txt", "w+") do |f|...end
Read and Write to a File
Since it’s related to the
IO class, the
File class can read and write files. It’s important to mention that the file must be opened before reading or writing can start. It must also be closed afterward.
To just write to a file, use the
example_file = File.open("exampleFile.txt", "w")File.write("exampleFile.txt", "This is some text.")example_file.close
To just read an (opened) file, use the
example_file = File.open("exampleFile.txt", "r")puts example_file.read# Output: This is some text.example_file.close
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Ruby on Codecademy
Front-End EngineerFront-end engineers work closely with designers to make websites beautiful, functional, and fast.
Includes 34 Courses
With Professional Certification