#12 Counting Words in a File (word_count.rb)

It’s often handy to know the number of words in a file. Word count is a standard feature in word-processing programs, but if you’re not using a word processor, obtaining a word count might not be so easy. I originally wrote this script when I was working on a project using an XML-based document production system called DocBook (http://www.docbook.org) and wanted to have a word count that roughly corresponded to those you could get from a word processor. The Unix command wc counts words, but the numbers it reported didn’t necessarily match what a word processor might report; the main reason probably had to do with issues like whether words with fewer than a certain number of letters should count as a ...

Get Ruby by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.