Search⌘ K

Count Words and Lines in a Text File

Explore how to create a Ruby program that reads a text file path from the command line and counts the words and lines within it. Understand command-line argument handling, string splitting for counting, and best practices for managing file paths to build a flexible file processing utility.

We'll cover the following...

Problem

Write a program that reads a file path from the command-line argument and counts the number of words and lines in that file.

ruby main.rb file.txt
file.txt contains 128 words in 13 lines
Counting words and lines in a text file

Purpose

  • Read command-line arguments

Analyze

This program is a generic utility, which means we can use the program for different text files. Therefore, we cannot set the input file path. When running a program, we can pass arguments to the program. These arguments are called command-line arguments.

Hints

  • We ...