Ruby - Counting Words in Text File

Introduction

To get the number of words in the string, you can use the length or size array methods to count the number of elements rather than join them together:

puts "this is a test".scan(/\w+/).length #4 

Let's split the string by spaces and get the length of the resulting array, like so:

puts "this is a test".split.length 

By default, split will split by whitespace, single or multiple characters of spaces, tabs, newlines, and so on.

Demo

lines = File.readlines("main.rb") 
line_count = lines.size # from w  w w  .  j  a  v  a  2  s  . co  m
text = lines.join 

word_count = text.split.length 
puts "#{word_count} words"

Result

Related Topic