0
0
Rubyprogramming~15 mins

File.readlines for line-by-line in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading a File Line-by-Line with File.readlines in Ruby
📖 Scenario: You have a text file named colors.txt that contains a list of colors, one color per line. You want to read this file line-by-line to process each color.
🎯 Goal: Build a Ruby program that reads the colors.txt file line-by-line using File.readlines and prints each color in uppercase.
📋 What You'll Learn
Create a variable called colors that reads all lines from colors.txt using File.readlines
Create a variable called count and set it to 0
Use a for loop with variable color to iterate over colors
Inside the loop, print each color in uppercase
After the loop, print the total number of colors read
💡 Why This Matters
🌍 Real World
Reading files line-by-line is common when processing logs, configuration files, or data lists.
💼 Career
Many programming jobs require reading and processing text files efficiently, especially in scripting and automation.
Progress0 / 4 steps
1
Read all lines from the file
Create a variable called colors that reads all lines from the file colors.txt using File.readlines.
Ruby
Need a hint?

Use File.readlines('colors.txt') to read all lines into an array.

2
Create a counter variable
Create a variable called count and set it to 0 to count the number of colors.
Ruby
Need a hint?

Initialize count to zero before counting.

3
Loop through each color and print uppercase
Use a for loop with variable color to iterate over colors. Inside the loop, print each color in uppercase and increase count by 1.
Ruby
Need a hint?

Use for color in colors to loop. Use color.chomp.upcase to print uppercase without extra newlines.

4
Print the total number of colors
After the loop, print the total number of colors read using puts and the count variable.
Ruby
Need a hint?

Use puts "Total colors: #{count}" to print the count after the loop.