Ruby - Count Number of Words in a File

1. Introduction

Analyzing text data can be essential in various applications, ranging from content management systems to data analytics platforms. One basic operation in text analysis is counting the number of words in a given text file. This post will provide a concise guide to creating a Ruby program that counts the number of words in a file.

2. Program Steps

1. Open the desired file in reading mode.

2. Read the contents of the file.

3. Split the content based on spaces to segregate individual words.

4. Count the number of words.

5. Display the word count.

3. Code Program

# Specify the path of the file you want to check
file_path = "sample_file.txt"
# Initialize a word count variable
word_count = 0
# Open and read the file, "r") do |file|
  file.each_line do |line|
    # Split the line into words and update the word count
    word_count += line.split.size
# Print the word count
puts "The file #{file_path} has #{word_count} words."


The file sample_file.txt has 1500 words.


1. file_path = "sample_file.txt": This line specifies the file's path or name that you want to inspect.

2., "r") do |file|: We use the open method from the File class to open the specified file in reading mode.

3. file.each_line do |line|: This iterates through each line of the file.

4. word_count += line.split.size: For every line, we split it based on spaces using the split method, which gives an array of words. The size method then returns the number of words in that line, and we update our word_count accordingly.

5. puts "The file #{file_path} has #{word_count} words.": Finally, we display the total word count.