Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 52 / 68

File Reading and Writing Basics

In this lesson you will learn the basics of reading and writing files with File.write and File.read. This is for anyone searching for "Ruby file read write".

File.write writes a string to a file and File.read reads one back. Saving configuration files and logs makes this a basic operation you will use often. Completing a file operation in a single call is characteristically Ruby.

The sample code writes two lines of text with File.write("memo.txt", ...) and reads them back with File.read("memo.txt"). Notice how these two class methods alone cover basic file work.

A common stumbling block for beginners is writing code that ignores the possibility of failure. Combining it with exception handling makes for robust code that copes properly when the file is missing.

Checking existence with File.exist? before reading is another common safe pattern. Recording logs and managing configuration files are daily work in real Ruby applications.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)