Ruby - Counting Words in Text File


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.


lines = File.readlines("main.rb") 
line_count = lines.size #   w w w. j  a  va2  m
text = lines.join 

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


Related Topic