0
0
Rubyprogramming~30 mins

IO modes (r, w, a) in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Working with IO Modes (r, w, a) in Ruby
📖 Scenario: You are managing a simple text file that stores a list of favorite fruits. You want to practice reading from, writing to, and appending to this file using Ruby's IO modes.
🎯 Goal: Build a Ruby program that reads the initial content of a file, overwrites it with new content, then appends additional content, demonstrating the use of r, w, and a modes.
📋 What You'll Learn
Create a text file named fruits.txt with initial fruit names.
Read and display the content of fruits.txt using r mode.
Overwrite fruits.txt with new fruit names using w mode.
Append more fruit names to fruits.txt using a mode.
Print the final content of fruits.txt after all operations.
💡 Why This Matters
🌍 Real World
Managing text files is common for saving logs, user data, or configuration settings in many applications.
💼 Career
Understanding file input/output modes is essential for backend developers, data engineers, and anyone working with file systems.
Progress0 / 4 steps
1
Create the initial file with fruit names
Create a file named fruits.txt and write these exact lines into it: Apple, Banana, and Cherry, each on its own line. Use Ruby's File.open with mode "w" and puts to write the lines.
Ruby
Need a hint?

Use File.open with mode "w" to create and write to the file. Use puts to write each fruit on a new line.

2
Read and display the file content
Open fruits.txt in read mode "r" and read all lines into a variable called content. Then close the file.
Ruby
Need a hint?

Use File.open with mode "r" to read the file. Use read to get all content as a string. Don't forget to close the file.

3
Overwrite the file with new fruits
Open fruits.txt in write mode "w" and overwrite it with these exact fruits: Orange and Grape, each on its own line. Close the file after writing.
Ruby
Need a hint?

Use File.open with mode "w" again to overwrite the file. Write the new fruits with puts.

4
Append more fruits and print final content
Open fruits.txt in append mode "a" and add these fruits: Kiwi and Mango, each on its own line. Then open the file in read mode "r" and print the entire content stored in final_content.
Ruby
Need a hint?

Use File.open with mode "a" to add lines without erasing. Then read the file again and print the content.