[ next ] [ prev ] [ contents ] [ up to First Example ] Invitation To Ruby

Counting Lines in Multiple Files

Using libraries

Since countlines2.rb was written to support libraries, let's use that library to count lines in multiple files.

countfilelines.rb

  1: #!/usr/bin/env ruby
  2: 
  3: require 'countlines2'
  4: 
  5: for filename in ARGV
  6:   file = open(filename)
  7:   printf "%-20s %4d\n", 
  8:     filename, filelines(file)
  9:   file.close
 10: end

  • [3] require will search for the given file and load it (if it hasn't been loaded already).
  • [5] ARGV is the name of an array strings containing the command line arguments.
    • ARGV[0] returns the first array entry.
    • ARGV.size returns the number of elements in the array
  • [5-10] The for loop will repeat the body of the loop one time for each element of the array.
    • Each time, the variable filename will have the current element from ARGV.
  • [6] The open function opens the given file and returns a File object.
  • [7] The printf function formats the text.
    • Note that the line is continued automatically if Ruby can determine that the first line is incomplete.
  • [9] Don't forget to close the file.


[ next ] [ prev ] [ contents ] [ up to First Example ] Copyright 2002 by Jim Weirich.
All rights reserved.