LUG Programming

Page 62

79 80 81 82 83 84 85

Rdoc.usage exit 0 when '--min' min = arg.to_i end end

Lines 76 to 84 handle the options received. Here again, we use an iterator and a code block. Inside the code block there is a case ... when ... end statement. This is similar to the JavaScript switch ... case statement. Irrespective of the option style used, GetoptLong aways returns the long version. Here we test for the two predefined options. If the user asked for –-help we can make use of our documentation comments at the start of the file to explain what the user needs to do. This is achieved using the Rdoc.usage method on line 79. The Kernel module also provides an exit method which exits the program, returning an exit code, which we give as argument to the method (line 80). Programs that terminate successfully usually return positive values or 0, and use negative values to indicate that an error occurred. Line 82 converts the string argument to an integer. Note that if a non integer value is given, the value returned is 0. See ri String#to_i for more information. 86 87 88 89 90 91 92 93 94 95

if ARGV.length != 1 puts "Missing file_path argument (try -–help)" exit(-1) end path = ARGV.shift unless File.exists?(path) && File.file?(path) && File.readable?(path) puts "File path #{path} doesn't exist, isn't a file, or can't be read" exit(-1) end

Lines 86 to 89 check that the user has specified a file path, and if not, exits after printing an error message. The command line arguments are stored in the ARGV array, and by the time GetoptLong has finished, we should be left with just the file path. The exit statement on line 88 uses parentheses, because without them Ruby generates a warning. Line 90 removes the file path name from ARGV and stores it in the local variable path. Line 91 checks that the path exists, is a file, and can be read, using the keyword. Just to remind you: 91

unless

unless File.exists?(path) && File.file?(path) && File.readable?(path)

could also be expressed as: 91

if !File.exists?(path) || !File.file?(path) || !File.readable?(path)

I hope you agree with me that the unless statement is more readable. 96 puts WordCount.new(path, min).parse.to_s 97 exit 0 98 99 end

Finally, we can get down to doing the job. Line 96 creates a WordCount instance, parses the text, and prints the summary. Because our parse method returns self, we can chain these three method calls (new, parse and to_s) together on one line. Again, this is normal practice in Ruby. 62

Copyright Š John Leach 2008. All rights reserved.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.