0
0
Rubyprogramming~15 mins

File.open with block (auto-close) in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using File.open with block for auto-closing files
📖 Scenario: You are working on a small program that reads a list of names from a file and processes them safely.
🎯 Goal: Learn how to open a file using File.open with a block so the file automatically closes after reading.
📋 What You'll Learn
Create a text file named names.txt with specific names
Use File.open with a block to read the file
Process the file content inside the block
Print the processed result after reading
💡 Why This Matters
🌍 Real World
Reading and writing files safely is common in many programs, such as loading user data, configuration, or logs.
💼 Career
Knowing how to handle files properly with automatic closing is important for writing reliable Ruby applications and avoiding resource leaks.
Progress0 / 4 steps
1
Create the names.txt file with names
Create a file called names.txt and write these exact names separated by new lines: Alice, Bob, Charlie
Ruby
Need a hint?

Use File.write to create and write to the file in one step.

2
Set up a variable to hold the names list
Create an empty array called names to store the names read from the file
Ruby
Need a hint?

Use names = [] to create an empty array.

3
Read the file using File.open with a block and fill names
Use File.open('names.txt', 'r') with a block and inside the block use file.each_line to add each line stripped of whitespace to the names array
Ruby
Need a hint?

Use File.open with a block to ensure the file closes automatically.

4
Print the names array
Write puts names.inspect to display the names array content
Ruby
Need a hint?

Use puts names.inspect to print the array in a readable format.