Tuesday, December 17, 2013

How to parse command-line arguments in Ruby using OptionParser

I do my scripting in Ruby. I did a lot of scripting in Perl in the past. Usually people prefer getoptlong in Perl to elegantly process command-line arguments.

As with Ruby, there is more than one way to do a particular thing. Ruby has OptionParser.
OptionParser provides a beautiful framework for processing command-line arguments.

Here is a simple demonstration of its usage :-

#!/usr/bin/ruby

require 'optparse'
 
options = {} # Hash where all the options are stored
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: ./script -f "
  opts.on("-f INPUT_FILE", String,"regression list") do |a|
    options[:input_file] = a.chomp
  end
end

if ARGV.empty?  #In case no arguments are provided, help message is displayed
  puts optparse      #./script -h or --help also displays the usage information
  exit
else
  optparse.parse!
end

regression_list = options[:input_file]

< Rest of the code for dealing with the regression list and simulations etc.>

Note - if you use parse! then ARGV is taken as the input argument by default
If you choose to use parse, then you would have to supply the input list explicitly, e.g., ARGV

No comments:

Post a Comment