File Operations

I said earlier that regular expressions are often used to process data stored in files on disk. In some earlier examples, I read in data from a disk file, did some pattern matching, and displayed the results on the screen. Here is one more example in which I count the words in a file. You do this by scanning each line in order to create an array of words (that is, sequences of alphanumeric characters) and then adding the size of each array to the variable, count:


count = 0
File.foreach( 'regex1.rb' ){ |line|
    count += line.scan( /[a-z0-9A-Z]+/ ).size
puts( "There are #{count} words in this file." )

If you want to verify that the word count is correct, you could display a numbered list of words read in from the file. ...

Get The Book of Ruby 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.