Most command line applications usually accept a variety of options that can be passed in to alter the behaviour of the application. For example, in linux, the
find command can take a
-type d option to specify only search for directories. For example the following command will find all empty directories under
Ruby command line applications require the same functionality and this is provided using the
So lets start off with a simple example - a Ruby command line application that politely says ‘hello’ back the user! Why not! There are several basic things we need to do to get this working:
OptionParsermodule by using
on(an alias for
make_switch) for each option we want available in our application
onmethod also in turn takes a block where we can set the variable on the hash we created earlier
So here is our first example:
This is how to use the HelloParser class in Ruby …
… and call the application from the command line passing in the
Lets extend this basic application by introducing a second switch
-t which can indicate the number of times to say hello!
Notice the use of
OptionParser::OctalInteger in the second
-t option definition which will automatically convert the input from a
String to a
This is how to use the HelloParser class is now used in Ruby with the extra option. Note that we use a ternary operator to consider a default value of 1 if
-t is not set.
This is how the application is run on the command line:
Up til now we have not considered exception handling in our application. Since we are dealing with user input we should really be considering this. The location where exceptions can occor is in the
parse method of our
OptionParser instance so lets wrap that in a
begin..rescue block as follows:
Now we should be good to go and our
HelloParser will exit gracefully if there is an error.
The OptionParser module is a great and simple way to parse parameters for Ruby command line applications. The simple DSL of
on are intuitive and self explainatory. Convertion of types at the parser level is also pretty handy. Next time I write a command line application in Ruby I will certainly use the
Here is Gist with the full example code.