Ruby ARGV, options and OptionParser

2 Oct 2009

A nice Ruby example (for my reference) showing how to parse commandline options; the results are put in a hash called options (created on line 3).

Interestingly, the ARGV array is automatically extended to include the options method even before require ‘optparse’ is run. See also ri OptionParser and From Pragmattic Programmers’ Best of Ruby Quiz:

if __FILE__ == $0
  require 'optparse'
  options = { :size => 2 }
  number = ARGV.pop

  ARGV.options do |opts|
    script_name = File.basename($0)
    opts.banner = "Usage: ruby #{script_name} [options] number"

    opts.separator ""

    opts.on("-s", "--size size", Numeric,
      "Specify the size of line segments.",
      "Default: 2"
    ) { |options[:size]| }

    opts.separator ""

    opts.on("-h", "--help", "Show this help message.") { puts opts; exit }


comments powered by Disqus

  « Previous: Next: »